To get the type of a variable in Java, you can use the getClass()
method, which is inherited from the Object
class. This method returns an instance of the Class
class, which represents the type of the object.
Here's an example of how you could use the getClass()
method to get the type of a variable:
Object obj = "hello"; Class cls = obj.getClass(); System.out.println("Type of variable: " + cls.getName());
This code will output "Type of variable: java.lang.String", because the object is a String
.
You can also use the instanceof
operator to check if a variable is an instance of a specific type. For example:
if (obj instanceof String) { System.out.println("Variable is a string"); } else if (obj instanceof Integer) { System.out.println("Variable is an integer"); }
This code will output "Variable is a string" because the object is a String
.
Note that the instanceof
operator only works for objects, not primitives. To check the type of a primitive value, you can use the typeof
operator in JavaScript or the typeid
operator in C++. In Java, you can use the getType()
method of the Class
class to get the type of a primitive value. For example:
int value = 42; Class cls = int.class; System.out.println("Type of variable: " + cls.getTypeName());
This code will output "Type of variable: int".