Search code examples
javainstanceoftypechecking

How can I get this Java instanceof test to return false rather than an error?


I have been experimenting with instanceof in my Java code.

public class Test {
    public static void main(String[] args) {
        String favoriteFood = "sandwich";
        boolean flag = favoriteFood instanceof StringBuilder; //incompatible types
    }
}

I get an error from flag because String cannot be cast to StringBuilder. I understand that testing a String to check if it is an instance of StringBuilder is illogical because Strings can never be cast as StringBuilders. I also understand the benefits of failing fast. However, is there any way to still run this test and return false? I have looked at related posts, but they have more to do with why there is an error than what to do about it.

(I know there is no practical need to do this. I just want to know if this can be done. If yes, then how? If not, then why not?)


Solution

  • The answer to If not, then why not? is "because the language spec says so" (see comment by Carlos H.).

    And the answer to "why does the language spec say so" is that language definers have this tendency to outlaw constructs that make no sense whenever they can, and this tendency is inspired by their belief that in doing that, they are helping you to write better code.

    EDIT

    re. "does defining a boolean as (2 + 2 == 5) make any more logical sense than ..." : no, it doesn't, but :

    (a) it is impossible (that is, logistically infeasible) for language definers to inventorize all the things that could be written but make no logical sense (*)
    (b) this kind of problem boils down to proving the emptiness of a set (e.g. proving that the set of all possible instances of String that are also instances of StringBuilder is empty) and proving the emptiness of a set in general as a problem is NP-hard. Given specific extra information, it might be possible and is sometimes done, e.g. given a type hierarchy that almost literally says "no String can also be a StringBuilder". But in general, that is undoable. Which is why you'll always find cases if only you keep searching hard enough.

    (*) For your sense of "logical sense", but what you (/we all) really mean, is really just "good programming practice", one of which would be "avoiding obfuscated ways of writing false". It might seem counterintuitive to you, but logic has no concept of "logical sense". 2+2==5 is just another logical proposition, and it happens to be false. Logic does not complain about falsehoods, it just observes them.

    (PS I know I used "makes no sense" too, shouldn't have, but I allowed myself to get carried away.)