How do you know a variable type in java?
You can use the instanceof
operator to determine the type of a variable in Java. Here is an example:
Object obj = "hello";
if (obj instanceof String) {
String str = (String) obj;
// do something with the string
}
You can also use the getClass()
method of the Object
class to get the Class
object for the variable, and then use the getName()
method of the Class
object to get the fully qualified name of the class as a String
. For example:
Object obj = "hello";
Class cls = obj.getClass();
String className = cls.getName();
System.out.println(className); // prints "java.lang.String"