You can cast null
to any reference type without getting any exception.
The println
method does not throw null pointer because it first checks whether the object is null or not. If null then it simply prints the string "null"
. Otherwise it will call the toString
method of that object.
Adding more details: Internally print methods call String.valueOf(object)
method on the input object. And in valueOf
method, this check helps to avoid null pointer exception:
return (obj == null) ? "null" : obj.toString();
For rest of your confusion, calling any method on a null object should throw a null pointer exception, if not a special case.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…