• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

A question about casting... .

 
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Ranch Hand
Posts: 381
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Enthuware Software Support
Posts: 4818
52
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Uh oh, we're definitely being carded. Here, show him this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic