This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Please read this line from "CHAPTER 5 Conversions and Promotions" in the link "http://www.infospheres.caltech.edu/resources/langspec-1.0/5.doc.html"
it says ------------------------------------------------------------------------- 5.1.4 Widening Reference Conversions The following conversions are called the widening reference conversions:
From any class type S to any class type T, provided that S is a subclass of T. (An important special case is that there is a widening conversion to the class type Object from any other class type.) From any class type S to any interface type K, provided that S implements K. From the null type to any class type, interface type, or array type. From any interface type J to any interface type K, provided that J is a subinterface of K. From any interface type to type Object. From any array type to type Object. From any array type to type Cloneable. From any array type SC to any array type TC, provided that SC and TC are reference types and there is a widening conversion from SC to TC.
Many developers are unaware that you may cast a null to ANY object. To extend Satou's example, the following is perfectly legal code:
You are, in effect, casting "from the null type to any class type, interface type, or array type".
The most obvious use of this is casting a value returned from a collection class, e.g.:
This code will not fail with a NullPointerException even if the key value is null unlike the following code:
which will throw a NullPointerException if the key value is null, i.e. you cannot invoke toString() on a null value. Therefore, the first example is safer in that you only need test for null after retrieving the value from the collection.
Another potential use for this capability is if you have constructors or overloaded methods that have a like number of parameters, e.g. each takes a single parameter, either an Integer or a String. You cannot invoke either constructor or method directly with null because the compiler will not know which you mean. But you may code something like the following:
to force the compiler to invoke the constructor (in this example) that accepts a single String parameter.