Reputation: 16628
Why this is a compile-time error when Java does the Autoboxing? Am I missing something?
int primitiveIntVariable = 0;
if (primitiveIntVariable instanceof Integer) {
}
I get
Inconvertible types; cannot cast 'int' to 'java.lang.Integer'
Upvotes: 6
Views: 26152
Reputation: 159086
int
cannot be anything but an int
, so the entire concept of using instanceof
is meaningless, and misguided.
You only use instanceof
if you need to check if the actual object is a particular type different from the type of the variable in question (or known supertypes hereof).
E.g. if the declared type of the variable (or the return value, or the compile-type of expression), is Integer
, then it makes no sense whatsoever to check it is an instanceof
of Integer
. Given that Java is type-safe, you already know that it is.
Similarly, it makes no sense whatsoever to check if a known Integer
is an instanceof
of Number
. You already know that it is.
And it makes even less sense to check if a known int
is an instanceof
of Integer
. It's a primitive, and you know it is, so there is absolutely no way it can be an instance of any object type.
The last will generate a compiler error. The first two examples are compiler warnings, which is very evident if you use any good IDE. Always use a good IDE, because they catch so many dumb mistakes we all happen to write occasionally.
So the above was an explanation of why it makes no sense to even try, but even though integerVar instanceof Integer
makes no sense, it compiles ok, but intVar instanceof Integer
fails to compile, so why it that?
The reason is actually related to this mistaken statement in the question:
when Java does the Autoboxing
Java doesn't do autoboxing everywhere. Autoboxing only happens in:
Integer x = 5
foo(5)
where parameter is an Integer
(Integer) 5
or (Object) 5
It does not happen by itself in the middle of an expression, and instanceof
is an expression operator.
But, more specifically, it fails to compile because JLS 15.20.2. Type Comparison Operator instanceof
says so:
RelationalExpression
instanceof
ReferenceTypeThe type of the RelationalExpression operand of the
instanceof
operator must be a reference type or the null type, or a compile-time error occurs.
Upvotes: 5
Reputation: 6017
As the name suggests, instanceof means an instance (object) of a class. Primitive datatypes are not instances.
This is how you get the class for a primitive datatype:
int i = 1;
System.out.println(((Object)i).getClass().getName());
// prints: java.lang.Integer
So instead of instanceof, use isInstance(...) like this:
Integer.class.isInstance(1); // returns true
Integer.class.isInstance(1.2); // returns false
Hope this helps. Good luck.
Upvotes: 11