How to check type of variable in Java?
To check the type of a variable in Java, you can use the instanceof
operator.
The instanceof
operator returns true
if the object on the left hand side is an instance of the class or interface on the right hand side, and false
otherwise.
Here is an example of how to use the instanceof
operator to check the type of a variable:
Object obj = "hello";
if (obj instanceof String) {
System.out.println("obj is a String");
} else if (obj instanceof Integer) {
System.out.println("obj is an Integer");
} else {
System.out.println("obj is something else");
}
This will print "obj is a String" because the object stored in the obj
variable is a String
object.
You can also use the getClass
method of the Object
class to get the runtime type of a variable:
Object obj = "hello";
Class cls = obj.getClass();
System.out.println("obj is an instance of " + cls.getName());
This will print "obj is an instance of java.lang.String".
Keep in mind that these methods only work for object references, not for primitive types such as int
or boolean
. To check the type of a primitive value, you can use the typeof
operator or use type casting.
For example:
int x = 123;
if (x instanceof Integer) { // compilation error
// ...
}
if (x instanceof int) { // compilation error
// ...
}
if (x instanceof Object) { // compilation error
// ...
}
if (x instanceof Number) { // compilation error
// ...
}
if (x instanceof Double) { // compilation error
// ...
}
if (x instanceof int[]) { // compilation error
// ...
}
if (x instanceof Integer[]) { // compilation error
// ...
}
if (x instanceof String[]) { // compilation error
// ...
}