How to Check Object Type in Java
See Java: Tips and Tricks for similar articles.
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 Objectand stores even numbers as strings and odd numbers as integers (using theIntegerwrapper class). The program then processes the array one item at a time in order to store each item as anintdata type. Theinstanceofoperator is used to determine if the array item is anIntegeror aString. For strings, you must first narrow theObjectto string (see line 8 in the source code) and then use theparseIntmethod of theIntegerclass (line 9). For integers, a narrowing must be performed on theObjectdata type to store the value as anintdata 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
instanceofoperator was used successfully to determine the object type of each array element and therefore permits a correct conversion of the data type toint.
