How to check object type in Java?

To check object type in Java, use instanceof operator or getClass() method.

instanceof

instanceof operator checks through the whole inheritance tree:

Object string = "Hello World!";
Object list = new java.util.ArrayList();

// true
System.out.println(string instanceof String);

// true
System.out.println(list instanceof java.util.Collection);

// true
System.out.println(list instanceof java.util.ArrayList);

// false
System.out.println(list instanceof java.util.Set);

getClass

getClass method returns the actual class of an object:

Object string = "Hello World!";
Object list = new java.util.ArrayList();

// class java.lang.String
System.out.println(string.getClass());

// class java.util.ArrayList
System.out.println(list.getClass());

// false
System.out.println(list.getClass() == java.util.Collection.class);

// true
System.out.println(list.getClass() == java.util.ArrayList.class);