Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

instanceof in Java - why doesn't this compile? [duplicate]

Tags:

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?

like image 916
UnderDog Avatar asked Aug 31 '13 13:08

UnderDog


People also ask

Is it good to use Instanceof in java?

Probably most of you have already heard that using “instanceof” is a code smell and it is considered as a bad practice. While there is nothing wrong in it and may be required at certain times, but the good design would avoid having to use this keyword.

How does Instanceof works in java?

The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .

What does Instanceof return in java?

The java instanceof operator is used to test whether the object is an instance of the specified type (class or subclass or interface). The instanceof in java is also known as type comparison operator because it compares the instance with type. It returns either true or false.

What can I use instead of Instanceof in java?

Having a chain of "instanceof" operations is considered a "code smell". The standard answer is "use polymorphism".


1 Answers

It's a compilation error in accordance with JLS §15.20.2:

If a cast of the RelationalExpression to the ReferenceType would be rejected as a compile-time error, then the instanceof relational expression likewise produces a compile-time error. In such a situation, the result of the instanceof expression could never be true.

RelationalExpression is the first operand of instanceof and ReferenceType is the second.

like image 168
arshajii Avatar answered Sep 20 '22 11:09

arshajii