Check Type of a Variable in Java
Hassan Saeed
Dec 10, 2020
Oct 01, 2020

This tutorial discusses the method to check the type of a variable in Java.
Use getClass().getSimpleName()
to Check the Type of a Variable in Java
We can check the type of a variable in Java by calling getClass().getSimpleName()
method via the variable. The below example illustrates the use of this function on non-primitive data types like String
.
public class MyClass {
public static void main(String args[]) {
String str = "Sample String";
System.out.println(str.getClass().getSimpleName());
}
}
Output:
String
The below example illustrates the use of this method on an array.
public class MyClass {
public static void main(String args[]) {
String[] arr = new String[5];
System.out.println(arr.getClass().getSimpleName());
}
}
Output:
String[]
This method is callable by objects only; therefore, to check the type of primitive data types, we need to cast the primitive to Object
first. The below example illustrates how to use this function to check the type of non-primitive data types.
public class MyClass {
public static void main(String args[]) {
int x = 5;
System.out.println(((Object)x).getClass().getSimpleName());
}
}
Output:
Integer