Friday, 15 July 2011

java - returning null through conditional operator when return value is int -


Can anyone explain the output of this code?

  public class main {int temp () {return (true? Zero: 0); } Public static zero main (string [] args) {main = new main (); Println (m.temp ()); }}    

We can take it one by one:

First compilation: Why does it compile successfully? Take a look at the code below:

  int getIntValue () {new integer (0)); // Note that I'm returning a reference here and so can also pass a null. }   

Unboxing happens here and you see this code compile properly. Even this code runs fine too.

Now coming to your code:

  int temp () {return (true? Null: 0); }   

Here are some things, first it is using a ternary operator, the Java specification says that if any type of operand type is T and other operations, then primitive, primitive autobox The first is the result of the operation and the type is returned. And so here, there is the first cover for the integer (autoboxed) and is basically converted to the integer type (remember, we can pass the null here) Now when you pass the blank as return type, So on the runtime, this int goes for type of premix.

So what we are basically doing is below:

  int i = (int) null;   

and the above code basically gives you nullpointerexception.

No comments:

Post a Comment