To check the type of a primitive value in Java, you can use the instanceof
operator. However, this operator can only be used to check the type of an object, not a primitive value.
Here is an example of how you can use the instanceof
operator to check the type of an object:
Integer i = 10; if (i instanceof Integer) { System.out.println("i is an instance of Integer"); }
To check the type of a primitive value, you can use the typeof
operator, which is a unary operator that returns a Class
object representing the type of the operand.
Here is an example of how you can use the typeof
operator to check the type of a primitive value:
int i = 10; Class type = typeof(i); System.out.println(type); // Outputs "int"
Alternatively, you can use the getClass()
method of the Object
class, which returns the Class
object for the object.
Here is an example of how you can use the getClass()
method to check the type of a primitive value:
int i = 10; Class type = i.getClass(); System.out.println(type); // Outputs "int"
Note that the getClass()
method is not available for primitive types in Java. To use this method, you will need to wrap the primitive value in an object of its corresponding wrapper class, such as Integer
for an int
value.
For example:
int i = 10; Integer iWrapper = i; Class type = iWrapper.getClass(); System.out.println(type); // Outputs "class java.lang.Integer"