No Exception while type casting with a null in java

java, nullpointerexception, typecasting-operator

Solution

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.

Problem

``` String x = (String) null; ``` Why there is no exception in this statement? ``` String x = null; System.out.println(x); ``` It prints `null`. But `.toString()` method should throw a null pointer exception.

Original source