|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
The instanceof Operator in Java
The instanceof operator is used to check whether and object belongs to a certain class. In other words, it is only used on reference types, not on primitive types (but it can be used on primitive types wrapper classes). The left operand of the expression is the reference to the object to check, and the right operand is the class name. |
String str = "abcde"; Object obj = null; if (str instanceof String) System.out.println("Found an instance of java.lang.String"); if (str instanceof Object) System.out.println("Found an instance of java.lang.Object"); System.out.println(obj instanceof Object); |
Since java.lang.String is derived from java.lang.Object and the instanceof operator always return false on a null instance, the output looks like this: |
Found an instance of java.lang.String Found an instance of java.lang.Object false |
| Previous | Next | |
Tutorial Home | ||
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
