Interview Q&A · Java · 5 questions in this topic

instanceof and null — Java Interview Q&A

All Java topics

What the instanceof check guarantees and what a null reference really means. Part of OOP Mechanics · 294 questions in the Java bank.

What does the instanceof operator do?

Answer

The instanceof operator tests the runtime type of an object and returns true when the reference can be cast to the target type. The syntax is reference instanceof Type, and the result is false when the reference is null instead of throwing an exception. The compiler rejects checks between unrelated types with an incompatible-types error, so only plausible casts compile. Since Java 16, pattern matching form such as if (obj instanceof String s) both tests and casts in one step.

Key points

  1. 1Returns false for null rather than throwing.
  2. 2Requires a plausible subtype relationship or compilation fails.
  3. 3Pattern variables from Java 16 remove the explicit cast.
  4. 4Because null always fails the test, instanceof doubles as a null-safe guard before a cast.
  5. 5A check against an interface always compiles, since any class could implement it at runtime.

Example

Example.javajava
Object x = "hello";
if (x instanceof String s) {
    System.out.println(s.toUpperCase());
}

What does null mean in Java?

Answer

null is a literal meaning a reference variable points to no object at all. Calling a method or reading a field through a null reference throws a NullPointerException at runtime. Only reference types can be null, while primitives such as int and boolean always hold a value and can never be null.

Example

Example.javajava
Employee e = null;
if (e == null) {
    System.out.println("no object yet");
}

What does instanceof return for a null reference?

Answer

false, always, and it never throws. The operator asks whether the reference points at an instance of that type, and null points at no instance, so the answer is false for every type including Object. That makes instanceof a null-safe check, unlike a cast or a method call, which is why the null check can be folded into the type test instead of being written separately.

Key points

  1. 1null instanceof AnyType is false.
  2. 2No exception is thrown for the null case.
  3. 3The check is null-safe; the following cast is not needed separately.
  4. 4null is assignable to any reference type but is an instance of none.

Learn this topic

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits