wood burning stoves 2.0
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes A question about casting... . Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "A question about casting... ." Watch "A question about casting... ." New topic

A question about casting... .

Rafa Barcel� Bauz�

Joined: Aug 09, 2006
Posts: 22
Why is this OK???

String s = (String) null;

How is possible that null, which is not an object can be "casted" to String???

Sanjeev Singh
Ranch Hand

Joined: Nov 01, 2006
Posts: 381
"null" is not a keyword not an object, but a special literal of the null type. It can be cast to any reference type, but not to any primitive type such as int or boolean. The null literal doesn't necessarily have value zero. Also,it is impossible to cast to the null type or declare a variable of this type.
Apart from its cast to String type it can also be casted to any array type,which is again a reference type.

~Sanjeev Singh<br />SCJP 1.5
Paul Anilprem
Enthuware Software Support
Ranch Hand

Joined: Sep 23, 2000
Posts: 3634
That's right. true, false, and null are literals. But they can be thought of as keywords to determine whether they can be used as variables names (which means no).

As per JLS,

A value of the null type (the null reference is the only such value) may be assigned to any reference type, resulting in a null reference of that type.

See section 5.2 here: http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.5

Enthuware - Best Mock Exams and Questions for Oracle Java Certifications
Quality Guaranteed - Pass or Full Refund!
I agree. Here's the link: http://aspose.com/file-tools
subject: A question about casting... .
It's not a secret anymore!