Java Reference
In-Depth Information
Employee e2 = new Employee("john", null);
Employee e3 = new Employee("john", "doe");
System.out.println(e3.getName());
}
}
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.)
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");
(
java Employee
). You should observe the following output:
null
lastName shouldn't be null
John Doe
nullsafetybyreducingthelikelihood ofa
NullPointerException
beingthrown
unintentionally. As another example,
Employee e = null; String s =
e.toString();
results in a thrown
NullPointerException
instance because