Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ? null : 0);  
   }


public static void main(String[] args)
{
    Main m=new Main();
    System.out.println(m.temp());
 }
}
like image 495
Praveen Kumar Avatar asked Aug 04 '26 12:08

Praveen Kumar


2 Answers

Lets take this one by one:

first compilation: why does it compile successfully? Have a look at below code:

int getIntValue(){

return new Integer(0));//note that i am returning a reference here and hence even I can possibly pass a null. 

}

Here unboxing happens and you see this code compiling properly. Even this code runs fine.

Now coming to your code:

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

Couple of things here, first this is making use of ternary operator. Java specification says that if any operand is of type T and other operand is primitive, primitive is first autoboxed and type T is returned as a result of the operation. And hence here, 0 is first wrapper (autoboxed) to Integer and than return type is basically converted to Integer type(remember, we can pass null here). Now when you pass null as return type, at runtime this is casted to int premitive type.

So what we are basically doing is as below:

int i =(int)null; 

And above code basically gives you nullpointerexception.

like image 192
zerocool Avatar answered Aug 06 '26 02:08

zerocool


Can anyone explain the output of this code ?

This will always through a NullPointerException . Trying to unbox null to int is a NullPointerException.

return(true ? null : 0); 

The condition is always true and hence the return expression evaluates to null. The second and third operands are null and 0 respectively. Since null can be a value of a reference , the entire expression will be typed to Integer as it is the closest match to 0 and null . Since the return type is primitive int and hence the Integer null reference should be unboxed to int , while doing that it should throw NPE as int cannot hold null , but Integer can.

Refer the JLS.

The type of a conditional expression is determined as follows:

  1. If one of the second and third operands is of primitive type T, and the type of the other is the result of applying boxing conversion (§5.1.7) to T, then the type of the conditional expression is T.

  2. If one of the second and third operands is of the null type and the type of the other is a reference type, then the type of the conditional expression is that reference type.

like image 22
AllTooSir Avatar answered Aug 06 '26 02:08

AllTooSir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!