43. Checking null references and returning non-null default references

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(). Both of them take two arguments—the reference to check for nullity, and the non-null default reference to return in case the checked reference is null:

public class Car {

private final String name;
private final Color color;

public Car(String name, Color color) {

this.name = Objects.requireNonNullElse(name, "No name");
this.color = Objects.requireNonNullElseGet(color,
() -> new Color(0, 0, 0));
}
}

In the preceding example, these methods are used in a constructor, but they can be used in methods as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.5.57