class A { public static void main(String...args) { Integer var = 10; if(var instanceof Character) // Line1 System.out.println("var is a Character"); } } I know Line 1 will not compile because the compiler has found that var is not a Character.
What I fail to understand is why the compiler throws an error instead of returning false or true.
If the compiler returns false or true (i.e treating the instanceof operation like a regular if-based validation), then it be much more useful.. would it not?
Or am I missing something obvious?
Integer var = 10;toObject var = 10;. The compiler is telling you thatvarcan never beinstanceof Characterif you declare it anInteger.instanceofcheck but instead of throwing an error it will returnfalse, you could tryCharacter.class.isInstance(var)which will return false in this case.varis anIntegerwhy on earth would you then want to check that it isn't? Unless you have an exceptionally short memory...varis anIntegerso theinstanceofcheck is obviously pointless) but I think he just wants to generally know the reasoning behind it.