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
Objectand stores even numbers as strings and odd numbers as integers (using the
Integerwrapper class). The program then processes the array one item at a time in order to store each item as an
intdata type. The
instanceofoperator is used to determine if the array item is an
String. For strings, you must first narrow the
Objectto string (see line 8 in the source code) and then use the
parseIntmethod of the
Integerclass (line 9). For integers, a narrowing must be performed on the
Objectdata type to store the value as an
intdata 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 to