How to Check Type of Variable in Java

How do you know a variable type in java?


How to check type of a variable in Java?

The type of a local variable is only available in debugging information.

You can;

  • compile with debugging information.
  • read the byte code for the debugging information and work out which one you are looking for.

NOTE: You can see this information in your debugger at runtime without writing any code.

However, a much simpler solution is to write a program such that you don't need to know this. e.g. store the data in a field instead of a local variable.

typeof in Java 8

You can use the getClass() method to get the type of the object you are using:

Object obj = null;
obj = new ArrayList<String>();

obj = "dummy";

obj = 4;

This will generate the following output:

class java.util.ArrayList
class java.lang.String
class java.lang.Integer

As you see it will show the type of the object which is referenced by the variable, which might not be the same as the type of the variable (Object in this case).

For primitive types there is no solution available as the problem of knowing the type stored in a variable does not exist. A primitive type variable can hold only values of that type. As you have to define the variable (or parameter) somewhere you already know the type of it and the values it can hold. There is no "base" type for primitive values which you can use similar to the Object type, which is the base type for all objects in java.

Use variable to any type and check type of this in Java?

Use the instanceof operator.

For example:

if (o instanceof Integer) {
//do something
} else if (o instanceof String) {
//do something else
} else if (o instanceof Object[]) {
//or do some other thing
} else if (o instanceof SomeCustomObject) {

Java : What is the best way to check variable type in runtime?

try this code :

if(floatVariable instanceof Float){}
if(intVariable instanceof Integer){}
if(stringVariable instanceof String){}

Print the type of a Java variable

Based on your example it looks like you want to get type of value held by variable, not declared type of variable. So I am assuming that in case of Animal animal = new Cat(); you want to get Cat not Animal.

To get only name without package part use

String name = theVariable.getClass().getSimpleName(); //to get Cat


String name = theVariable.getClass().getName(); //to get

Related Topics

Leave a reply