0Pricing
Java Academy · Lesson

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);  // false

All lessons in this course

  1. Primitive vs Reference Types
  2. Widening and Narrowing Conversions
  3. The instanceof Operator
  4. Type Casting in Practice
← Back to Java Academy