September 2019
Intermediate to advanced
816 pages
18h 47m
English
A solution to this problem can easily be provided via if-else (or the ternary operator), as in the following example (as a variation, name, and color can be declared as non-final and initialized with the default values at declaration):
public class Car { private final String name; private final Color color; public Car(String name, Color color) { if (name == null) { this.name = "No name"; } else { this.name = name; } if (color == null) { this.color = new Color(0, 0, 0); } else { this.color = color; } }}
However, starting with JDK 9, the preceding code can be simplified via two methods from the Objects class. These methods are requireNonNullElse() and requireNonNullElseGet() ...