Intellipaat 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.

2 Answers

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.

0 votes
by (1.8k points)

In Java when we try to typecast a null reference to some other data type then No CastClassException will be thrown Therefore,the inbuilt println method does not throw the null pointer exception because it first checks whether the object is null or not. If it is null it will directly print the string “null” otherwise it will call the ToString purpose of that particular object.

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

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...