0 votes
1 view
in Java by (8.2k points)

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.

1 Answer

0 votes
by (41k points)

You can cast null to any source type without preparing any exception.

The println method does not throw the null pointer because it first checks whether the object is null or not. If null before it simply prints the string "null". Otherwise, it will call the toString purpose of that object.

Adding more further details: Inside print methods call String.valueOf(object) method on the input object. And in the valueOf method, this check helps to bypass null pointer exception:

return (obj == null) ? "null" : obj.toString();

For the rest of your embarrassing, calling any system on a null object should throw a null pointer exception, if not a special case.

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...