How to check type of variable in Java?

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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.

Solution 2 - Java

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 );

Solution 3 - Java

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: https://stackoverflow.com/questions/2674554/how-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/

Solution 4 - Java

Just use:

.getClass().getSimpleName();

Example:

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

Output:

StringBuilder

Solution 5 - Java

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){...}

Solution 6 - Java

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.

Solution 7 - Java

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.

Solution 8 - Java

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

Solution 9 - Java

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
	}

}

Solution 10 - Java

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());       
}

Solution 11 - Java

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 https://stackoverflow.com/questions/182636/how-to-determine-the-class-of-a-generic-type?noredirect=1&lq=1">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

Solution 12 - Java

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

Solution 13 - Java

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

Solution 14 - Java

public static void chkType(Object var){		
		String type = var.getClass().toString();
		System.out.println(type.substring(16));		
		//assertEquals(type,"class java.lang.Boolean");
		//assertEquals(type,"class java.lang.Character");
		//assertEquals(type,"class java.lang.Integer");
		//assertEquals(type,"class java.lang.Double");		
	}

Solution 15 - Java

var.getClass().getSimpleName()

Let's take a example

String[] anArrayOfStrings = { "Agra", "Mysore", "Chandigarh", "Bhopal" };
List<String> strList = Arrays.asList(anArrayOfStrings); 

anArrayOfStrings.getClass().getSimpleName() //res =>  String[]
strList.getClass().getSimpleName() // res => ArrayList

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStrawberryView Question on Stackoverflow
Solution 1 - JavapkaedingView Answer on Stackoverflow
Solution 2 - JavaMvcoileView Answer on Stackoverflow
Solution 3 - JavaGlen PierceView Answer on Stackoverflow
Solution 4 - JavaDebayanView Answer on Stackoverflow
Solution 5 - JavaAlex AbdugafarovView Answer on Stackoverflow
Solution 6 - JavaAmoghView Answer on Stackoverflow
Solution 7 - Javauser207421View Answer on Stackoverflow
Solution 8 - JavaVinicius ArrudaView Answer on Stackoverflow
Solution 9 - JavaDoktorView Answer on Stackoverflow
Solution 10 - JavaNeil ReganView Answer on Stackoverflow
Solution 11 - Javaiggy12345View Answer on Stackoverflow
Solution 12 - JavaGeekyCoderView Answer on Stackoverflow
Solution 13 - JavaSlinnShadyView Answer on Stackoverflow
Solution 14 - JavaMr. LinsemanView Answer on Stackoverflow
Solution 15 - JavaParth kharechaView Answer on Stackoverflow