Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

int instanceof Integer

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'
like image 208
Vishrant Avatar asked Aug 28 '26 16:08

Vishrant


1 Answers

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.

like image 60
Harshal Parekh Avatar answered Aug 31 '26 08:08

Harshal Parekh