Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

explicit cast of null literal

 
Karin Paola Illuminate
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
[Khalid, p.43]
The cast construct has the following syntax:

Casting the reference literal null, which is not of any type, to a reference type results in a compile time warning.
I don't understand this sentence. I tried to cast a null value to a reference type, and it DID compile.

Can someone explain what I'm doing wrong?
Thanks.
[ April 07, 2003: Message edited by: Karin Paola Illuminate ]
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What version of Java are you running? My guess is that you're running something more recent than Java 1.2, which is what Mughal covers. From the JLS, I found this in §5.5 Casting Conversion:

The detailed rules for compile-time correctness checking of a casting conversion of a value of compile-time reference type S (source) to a compile-time reference type T (target) are as follows...
...If the value at run time is null, then the cast is allowed...

Now, I think it is quite possible that the compiler has been changed to no longer issue this warning. Unfortunately, I haven't found anything that comes right out and says so.
However, notice from Mughal's book that it states that the compiler will issue a "warning." A warning is very different from an error in that the program will still compile and execute with warnings, however, a single error will stop the application from compiling.
I hope that helps,
Corey
 
Marlene Miller
Ranch Hand
Posts: 1392
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the way to apply the example to JLS 5.5 is this:
1. The cast is not a compile-time error because the source type is the null type. The statements describing compile-time errors do not apply to the null type:
If S is a class type...
If S is an interface type...
If S is an array type...
2. The cast can be determined to be correct at compile time because
2A. By JLS 5.1.4, the conversion from the null type to a class type is a widening conversion.
2B. By JLS 5.2, assignment conversions allow widening conversions.
2C. JLS 5.5: A cast from the compile-time type S to compile-time type T is correct at compile time if and only if S can be converted to T by assignment conversion.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic