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.

  1. Open your text editor and type in the following Java statements:Java Source for Check Object Type ClassThe 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).
  2. Save your file as CheckObjectType.java.
  3. 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.Compile Source for Check Object Type Class
  4. 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.Run Tester for Derived Class