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.
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).
instanceofoperator was used successfully to determine the object type of each array element and therefore permits a correct conversion of the data type to