Friday, January 20, 2006

Java: can null be typecasted to String?

Will this compile and run without any ClassCastException?
 String s = (String) null;
System.out.println((String) null);
Wont typecasting null to String throw ClassCastException?

Answer: Both lines compile and run fine. null can be typecasted to any reference type. But the question is why is this behavoiur allowed?
Here's my explaination:
Consider following line of code.
  String s=null;
This compiles fine, so it means that the String reference can safely hold the value "null". Since null is an valid value for any reference type, casting it to that type will never throw a ClassCastException.

Have a better explaination? feel free to comment.

3 comments:

Anupam said...

I dont have a better explanation, but have to make one point.
"null" is no value, so its incorrect to say "since String s can hold null value, it could be typecasted to any type."

Also "null" is no reference, instead it does mean that reference is missing.
So, although i dont have a better explanation, but dont agree with your explanation. :)

Cheers !

Jayme (jdunlop @ gmail.com) said...

This has to do with method overloading. If I define two functions:

doSomething (String)
doSomething (BigInteger)

It will not compile if I call the following:

doSomething(null);

To prevent ambiguity compilation errors:

doSomething ((String)null);

Binh Nguyen said...

Thanks, nice post