Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 162
Avoiding a NullPointerException
ОглавлениеA more common example of where conditional operators are used is checking for null objects before performing an operation. In the following example, if duck is null, the program will throw a NullPointerException at runtime:
if(duck!=null & duck.getAge()<5) { // Could throw a NullPointerException // Do something }
The issue is that the logical AND (&) operator evaluates both sides of the expression. We could add a second if statement, but this could get unwieldy if we have a lot of variables to check. An easy-to-read solution is to use the conditional AND operator (&&):
if(duck!=null && duck.getAge()<5) { // Do something }
In this example, if duck is null, the conditional prevents a NullPointerException from ever being thrown, since the evaluation of duck.getAge() < 5 is never reached.