Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Java by (10.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 (46k 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.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Nov 25, 2019 in Java by Anvi (10.2k points)
+1 vote
4 answers

Browse Categories

...