[java] How to check type of variable in Java?

How can I check to make sure my variable is an int, array, double, etc...?

Edit: For example, how can I check that a variable is an array? Is there some function to do this?

This question is related to java

The answer is


public class Demo1 {

Object printType(Object o)
{
    return o;
}
 public static void main(String[] args) {

    Demo1 d=new Demo1();
    Object o1=d.printType('C');
    System.out.println(o1.getClass().getSimpleName());

}

}


The first part of your question is meaningless. There is no circumstance in which you don't know the type of a primitive variable at compile time.

Re the second part, the only circumstance that you don't already know whether a variable is an array is if it is an Object. In which case object.getClass().isArray() will tell you.


Just use:

.getClass().getSimpleName();

Example:

StringBuilder randSB = new StringBuilder("just a String");
System.out.println(randSB.getClass().getSimpleName());

Output:

StringBuilder

I hit this question as I was trying to get something similar working using Generics. Taking some of the answers and adding getClass().isArray() I get the following that seems to work.

public class TypeTester <T extends Number>{

<T extends Object> String tester(T ToTest){

    if (ToTest instanceof Integer) return ("Integer");
    else if(ToTest instanceof Double) return ("Double");
    else if(ToTest instanceof Float) return ("Float");
    else if(ToTest instanceof String) return ("String");
    else if(ToTest.getClass().isArray()) return ("Array");
    else return ("Unsure");
}
}

I call it with this where the myArray part was simply to get an Array into callFunction.tester() to test it.

public class Generics {
public static void main(String[] args) {
    int [] myArray = new int [10];

    TypeTester<Integer> callFunction = new TypeTester<Integer>();
    System.out.println(callFunction.tester(myArray));
}
}

You can swap out the myArray in the final line for say 10.2F to test Float etc


Basically , For example :

public class Kerem
{
    public static void main(String[] args)
    {
        short x = 10;
        short y = 3;
        Object o = y;
        System.out.println(o.getClass()); // java.lang.Short
    }

}

a.getClass().getName() - will give you the datatype of the actual object referred to by a, but not the datatype that the variable a was originally declared as or subsequently cast to.

boolean b = a instanceof String - will give you whether or not the actual object referred to by a is an instance of a specific class. Again, the datatype that the variable a was originally declared as or subsequently cast to has no bearing on the result of the instanceof operator.

I took this information from: How do you know a variable type in java?

This can happen. I'm trying to parse a String into an int and I'd like to know if my Integer.parseInt(s.substring(a, b)) is kicking out an int or garbage before I try to sum it up.

By the way, this is known as Reflection. Here's some more information on the subject: http://docs.oracle.com/javase/tutorial/reflect/


You may work with Integer instead of int, Double instead of double, etc. (such classes exists for all primitive types). Then you may use the operator instanceof, like if(var instanceof Integer){...}


I did it using: if(x.getClass() == MyClass.class){...}


Well, I think checking the type of variable can be done this way.

public <T extends Object> void checkType(T object) {    
    if (object instanceof Integer)
        System.out.println("Integer ");
    else if(object instanceof Double)
        System.out.println("Double ");
    else if(object instanceof Float)
        System.out.println("Float : ");
    else if(object instanceof List)
        System.out.println("List! ");
    else if(object instanceof Set)
        System.out.println("Set! ");
}

This way you need not have multiple overloaded methods. I think it is good practice to use collections over arrays due to the added benefits. Having said that, I do not know how to check for an array type. Maybe someone can improve this solution. Hope this helps!

P.S Yes, I know that this doesn't check for primitives as well.


None of these answers work if the variable is an uninitialized generic type

And from what I can find, it's only possible using an extremely ugly workaround, or by passing in an initialized parameter to your function, making it in-place, see here:

<T> T MyMethod(...){ if(T.class == MyClass.class){...}}

Is NOT valid because you cannot pull the type out of the T parameter directly, since it is erased at runtime time.

<T> void MyMethod(T out, ...){ if(out.getClass() == MyClass.class){...}}

This works because the caller is responsible to instantiating the variable out before calling. This will still throw an exception if out is null when called, but compared to the linked solution, this is by far the easiest way to do this

I know this is a kind of specific application, but since this is the first result on google for finding the type of a variable with java (and given that T is a kind of variable), I feel it should be included


Java is a statically typed language, so the compiler does most of this checking for you. Once you declare a variable to be a certain type, the compiler will ensure that it is only ever assigned values of that type (or values that are sub-types of that type).

The examples you gave (int, array, double) these are all primitives, and there are no sub-types of them. Thus, if you declare a variable to be an int:

int x;

You can be sure it will only ever hold int values.

If you declared a variable to be a List, however, it is possible that the variable will hold sub-types of List. Examples of these include ArrayList, LinkedList, etc.

If you did have a List variable, and you needed to know if it was an ArrayList, you could do the following:

List y;
...
if (y instanceof ArrayList) { 
  ...its and ArrayList...
}

However, if you find yourself thinking you need to do that, you may want to rethink your approach. In most cases, if you follow object-oriented principles, you will not need to do this. There are, of course, exceptions to every rule, though.


Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.

Example:

class Typetester {
    void printType(byte x) {
        System.out.println(x + " is an byte");
    }
    void printType(int x) {
        System.out.println(x + " is an int");
    }
    void printType(float x) {
        System.out.println(x + " is an float");
    }
    void printType(double x) {
        System.out.println(x + " is an double");
    }
    void printType(char x) {
        System.out.println(x + " is an char");
    }
}

then:

Typetester t = new Typetester();
t.printType( yourVariable );

You can check it easily using Java.lang.Class.getSimpleName() Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.

reference - Here is the Oracle docs link


I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.

//move your variable into an Object type
Object obj=whatYouAreChecking;
System.out.println(obj);

// moving the class type into a Class variable
Class cls=obj.getClass();
System.out.println(cls);

// convert that Class Variable to a neat String
String answer = cls.getSimpleName();
System.out.println(answer);

Here is a method:

public static void checkClass (Object obj) {
    Class cls = obj.getClass();
    System.out.println("The type of the object is: " + cls.getSimpleName());       
}