Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 159

null and the instanceof operator

Оглавление

What happens if you call instanceof on a null variable? For the exam, you should know that calling instanceof on the null literal or a null reference always returns false.

System.out.print(null instanceof Object); // false Object noObjectHere = null; System.out.print(noObjectHere instanceof String); // false

The preceding examples both print false. It almost doesn't matter what the right side of the expression is. We say “almost” because there are exceptions. This example does not compile, since null is used on the right side of the instanceof operator:

System.out.print(null instanceof null); // DOES NOT COMPILE

Although it may feel like you've learned everything there is about the instanceof operator, there's a lot more coming! In Chapter 3, we introduce pattern matching with the instanceof operator, which was officially added in Java 16. In Chapter 7, “Beyond Classes,” we introduce polymorphism in much more detail and show how to apply these rules to interfaces.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх