Nodir Nasirov Nodir Nasirov - 9 months ago 33
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
should return
right? In this case there should be
is an
, but this code does not compile.


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.