Java Reference
In-Depth Information
you cannot invoke toString() on the null reference stored in e . In contrast, Em-
ployee e = null; String s = Objects.toString(e); doesn'tresult
inathrown NullPointerException instancebecause Objects.toString()
returns "null" whenitdetectsthat e containsthenullreference.Ratherthanhaving
to explicitly test a reference for null, as in if (e != null) { String s =
e.toString(); /* other code here */ } ,youcanoffloadthenull-check-
ing to the Objects class's various methods.
dosoinanull-safemanner.Theinclusionof Objects inJava'sstandardclasslibrary
standardizes this common functionality.
Chapter 4 introduced you to the Math class's random() method. If you were to in-
vestigate this method's source code, you would discover the following implementation:
private static Random randomNumberGenerator;
private static synchronized Random initRNG()
Random rnd = randomNumberGenerator;
return (rnd == null) ? (randomNumberGenerator = new Ran-
dom()) : rnd;
public static double random()
Random rnd = randomNumberGenerator;
if (rnd == null) rnd = intRNG();
return rnd.nextDouble();
This implementation, which demonstrates lazy initialization (not initializing
something until it is first needed, in order to improve performance), shows you that
Math 's random() methodisimplementedintermsofaclassnamed Random ,which
is located in the java.util package. Random instances generate sequences of ran-
dom numbers and are known as random number generators .
Note Thesenumbersarenottrulyrandombecausetheyaregeneratedfromamath-
ematical algorithm. As a result, they are often referred to as pseudorandom numbers.
Search WWH ::

Custom Search