• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

A question about casting... .

 
Rafa Barcel� Bauz�
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is this OK???

String s = (String) null;

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


Thanks.
 
Sanjeev Singh
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"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.
 
Paul Anilprem
Enthuware Software Support
Ranch Hand
Posts: 3776
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic