Java Reference
In-Depth Information
Employee e2 = new Employee("john", null);
Employee e3 = new Employee("john", "doe");
System.out.println(e3.getName());
}
}
Listing 6-10 ' s Employee constructor first invokes Ob-
jects.requireNonNull() oneachargumentvaluepassedtoits firstName and
lastName parameters.Ifeitherargumentvalueisthenullreference, NullPointer-
Exception isinstantiatedandthrown;otherwise,the requireNonNull() method
returns the argument value, which is guaranteed to be nonnull.
It is now safe to invoke lastName.charAt() , which returns the first character
fromthestringonwhichthismethodiscalled.Thischaracterispassedto Character 's
toUpperCase() utilitymethod,whichreturnsthecharacterwhenitdoesnotrepres-
entalowercaseletter,ortheuppercaseequivalentofthelowercaseletter.After toUp-
perCase() returns,the(potentially uppercased)letterisprependedtotherestofthe
string,resultinginalastnamestartingwithanuppercaseletter.(Assumethatthename
consists of letters only.)
Listing6-10 ' s Objects.requireNonNull() methodcallsofferamorecompact
alternativetothefollowingexample,whichdemonstrateshow requireNonNull(T
obj, String message) 's message parameter is used:
if (firstName == null)
throw new NullPointerException();
if (lastName == null)
throw new NullPointerException("lastname shouldn't be
null");
Compile Listing6-10 ( javac Employee.java )andruntheresultingapplication
( java Employee ). You should observe the following output:
null
lastName shouldn't be null
John Doe
As Listing 6-10 reveals, the Objects class's methods were introduced to promote
nullsafetybyreducingthelikelihood ofa NullPointerException beingthrown
unintentionally. As another example, Employee e = null; String s =
e.toString(); results in a thrown NullPointerException instance because
Search WWH ::




Custom Search