The instanceof Operator
Use instanceof to check object types before casting and avoid ClassCastException.
The instanceof Operator
The instanceof operator checks whether an object is an instance of a given type at runtime. It returns true or false and prevents ClassCastException before casting.
Basic instanceof Usage
Use instanceof to test the runtime type of an object before performing a safe cast.
Object obj = "Hello, Java!";
if (obj instanceof String) {
String s = (String) obj;
System.out.println(s.toUpperCase()); // HELLO, JAVA!
}
Object num = Integer.valueOf(42);
System.out.println(num instanceof Integer); // true
System.out.println(num instanceof String); // falseAll lessons in this course
- Primitive vs Reference Types
- Widening and Narrowing Conversions
- The instanceof Operator
- Type Casting in Practice