Java instanceof Operator
Java instanceof operator (also called type comparison operator) is used to test whether the specified object is an instance of the specified type (class, subclass, or interface).
- true – if the variable is an instance of the specified class, its parent class or implements specified interface, or its parent interface
- false – if the variable is no instance of the class or implement the interface, or the variable is null.
HashMap map = new HashMap(); assertTrue( map instanceof Map ); assertTrue( map instanceof AbstractMap ); assertFalse( map instanceof List ); map = null; assertFalse( map instanceof Map );
1. Syntax of instanceof Operator
The instanceof operator tests variables to the specified type. Variable is written on the left-hand side of the operator, and type is given on the right side of the operator.
boolean value = variable instanceof ClassType; //or if(variable instanceof ClassType) < //perform some action >
2. The instanceof Operator does not need an Explicit null Check
In Java, null is a type so we do not need to check for NullPointerException when using the instanceof operator. The instanceof does it internally for us.
if(map != null && map instanceof Map) < //some action >
In the previous example, we do not need to make an explicit null check. The correct way to write the expression is:
3. Using instanceof with an Array
In Java, arrays are also considered objects and have associated fields and methods. So we can use instanceof operator with arrays as well.
Primitive arrays are instances of Object and self-type. e.g. int[] is type of Object and int[]. Both comparisons return true.
int[] intArr = new int[0]; Assertions.assertTrue(intArr instanceof Object); Assertions.assertTrue(intArr instanceof int[]);
Object arrays are types of Object, Object[], classtype array, and parent class type array. e.g. Integer[] is type of Object, Object[], Integer[] and Number[] ( Integer extends Number ).
Integer[] integerArr = new Integer[0]; Assertions.assertTrue(integerArr instanceof Object); Assertions.assertTrue(integerArr instanceof Object[]); Assertions.assertTrue(integerArr instanceof Integer[]); Assertions.assertTrue(integerArr instanceof Number[]);
A real-life example of using instanceof operator can be typecasting a variable to another type. The instanceof operator helps in avoiding ClassCastException in runtime.
Consider the following example where we are trying to typecast a list to LinkedList class, where the original variable is of type ArrayList. It will throw ClassCastException.
List list = new ArrayList<>(); LinkedList linkedList = (LinkedList) list; //ClassCastException
To correctly cast the variable, we can use instanceof operator. It will not result in ClassCastException.
List list = new ArrayList<>(); if(list instanceof LinkedList) < LinkedListlinkedList = (LinkedList) list; //other actions > else if(list instanceof ArrayList) < ArrayListarrayList = (ArrayList) list; //other actions >
Since Java 14, instanceof operator supports pattern matching. We can rewrite the above expression more concisely:
List list = new ArrayList<>(); if(list instanceof LinkedList linkedList) < //use linkedlist variable here >else if(list instanceof ArrayList arrayList) < //use arraylist variable here >
Drop me your questions related to the instanceof operator used for type comparison.
How to Check Object Type in Java
You can check object type in Java by using the instanceof keyword. Determining object type is important if you’re processing a collection such as an array that contains more than one type of object. For example, you might have an array with string and integer representations of numbers. You would need to determine the object type in order to store a given array item as an int data type. To learn how to check object type, follow these four steps.
- Open your text editor and type in the following Java statements:The program creates an array of type Object and stores even numbers as strings and odd numbers as integers (using the Integer wrapper class). The program then processes the array one item at a time in order to store each item as an int data type. The instanceof operator is used to determine if the array item is an Integer or a String . For strings, you must first narrow the Object to string (see line 8 in the source code) and then use the parseInt method of the Integer class (line 9). For integers, a narrowing must be performed on the Object data type to store the value as an int data type (line 13).
- Save your file as CheckObjectType.java .
- Open a command prompt and navigate to the directory containing your Java program. Then type in the command to compile the source and hit Enter .
- You will now test your program. Type in the command to run the Java runtime launcher and then hit Enter . Notice that the output of the program verifies that the instanceof operator was used successfully to determine the object type of each array element and therefore permits a correct conversion of the data type to int .
Related Articles
- How to Check Object Type in Java (this article)
- How to Create a Jar File in Java
- How to Compile Packages in Java
- How to Throw an Exception in Java
- How to Create an Exception Class in Java
- How to Use the super Keyword to Call a Base Class Constructor in Java
- How to Use the Comparator.comparing Method in Java 8
- How to Use System.in in Java
- How to Call an Interface Method in Java
- How to Add a Time Zone in the Java 8 Date/Time API
- How to Rethrow an Exception in Java
- How to Use the instanceof Operator with a Generic Class in Java
- How to Instantiate an Object in Java
- How to Filter Distinct Elements from a Collection in Java 8
- How to Create a Derived Class in Java
- How to Skip Elements with the Skip Method in Java 8
- How to Create a Java Bean
- How to Implement an Interface in Java
- How to Compare Two Objects with the equals Method in Java
- How to Set PATH from JAVA_HOME
- How to Prevent Race Conditions in Java 8
- How to Write a Block of Code in Java
- How to Display the Contents of a Directory in Java
- How to Group and Partition Collectors in Java 8
- How to Create a Reference to an Object in Java
- How to Reduce the Size of the Stream with the Limit Method in Java 8
- How to Write an Arithmetic Expression in Java
- How to Format Date and Time in the Java 8 Date/Time API
- How to Use Comparable and Comparator in Java
- How to Break a Loop in Java
- How to Use the this Keyword to Call Another Constructor in Java
- How to Write a Unit Test in Java
- How to Declare Variables in Java
- How to Override Base Class Methods with Derived Class Methods in Java
- How to Use Serialized Objects in Java
- How to Write Comments in Java
- How to Implement Functional Interfaces in Java 8
- How to Write Type Parameters with Multiple Bounds in Java
- How to Add Type and Repeating Annotations to Code in Java 8
- How to Use Basic Generics Syntax in Java
- How to Map Elements Using the Map Method in Java 8
- How to Work with Properties in Java
- How to Write while and do while Loops in Java
- How to Use the finally Block in Java
- How to Write for-each Loops in Java
- How to Create a Method in Java
- How to Continue a Loop in Java
- How to Handle Java Files with Streams
- How to Create an Interface Definition in Java
- How Default Base Class Constructors Are Used with Inheritance
Training Options
Course Catalog
Test object type in java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter