当返回值为int时,通过条件运算符返回null

Pra*_*mar 2 java autoboxing ternary-operator

任何人都可以解释这段代码的输出吗?

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


public static void main(String[] args)
{
    Main m=new Main();
    System.out.println(m.temp());
 }
}
Run Code Online (Sandbox Code Playgroud)

zer*_*ool 6

让我们一个接一个:

第一次编译:为什么编译成功?看看下面的代码:

int getIntValue(){

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

}
Run Code Online (Sandbox Code Playgroud)

这里发生了拆箱,你会看到这段代码正确编译.即使这个代码运行正常.

现在来看你的代码:

int temp()
   {
      return(true ? null : 0);  
   }
Run Code Online (Sandbox Code Playgroud)

这里有几件事,首先是利用三元运算符.Java规范说如果任何操作数是T类型而其他操作数是原始的,则原语首先被自动装箱,并且作为操作的结果返回类型T. 因此,0是第一个包装(autoboxed)到Integer,而返回类型基本上转换为Integer类型(记住,我们可以在这里传递null).现在,当您将null作为返回类型传递时,在运行时,这将转换为int premitive类型.

所以我们基本上做的是如下:

int i =(int)null; 
Run Code Online (Sandbox Code Playgroud)

上面的代码基本上给你nullpointerexception.