Nodir Nasirov Nodir Nasirov - 5 months ago 14
Java Question

Java using instanceof method on primitive type gives compiler error

I am learning Java, and I do not understand why the following code does not compile without error:

public class SecondClass{

public static void main(String[] args){
int number = 45;
if (number instanceof String) {
System.out.println("Not a String!");
}
}
}


Why do I get an error in my conditional operation? The
instanceof
should return
true
or
false
right? In this case there should be
false
since
number
is an
int
, but this code does not compile.

Answer

From section 15.20.2 of the JLS:

The type of the RelationalExpression operand of the instanceof operator must be a reference type or the null type; otherwise, a compile-time error occurs.

In your case, the case of the RelationalExpression operand is int, therefore you get a compile-time error.

Even if you had an expression of type Integer, you'd then run into:

If a cast (ยง15.16) 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.

Comments