No Exception while type casting with a null in java
You can cast null
to any reference type. You can also call methods which handle a null
as an argument, e.g. System.out.println(Object)
does, but you cannot reference a null
value and call a method on it.
BTW There is a tricky situation where it appears you can call static methods on null
values.
Thread t = null;
t.yield(); // Calls static method Thread.yield() so this runs fine.
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.