2013-06-21 44 views
2

任何人都可以解释此代码的输出吗?当返回值为int时通过条件运算符返回null

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


public static void main(String[] args) 
{ 
    Main m=new Main(); 
    System.out.println(m.temp()); 
} 
} 
+0

什么是输出? –

+1

[你有什么尝试](http://mattgemmell.com/2008/12/08/what-have-you-tried/)除了问我们吗?你有没有试图去调试它? –

+0

@Praveen如果你的问题也围绕它为什么它在运行时编译和失败,请检查我的意见低于 – zerocool

回答

-2

这将是NullPointerException,因为int不会被赋值为null

然而

,这段代码将始终返回null,因为在这里你总是规定的条件为true,三元的真真切切的一部分声明,即null将得到返回。

但这个工程

public class Test 
{ 

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


    public static void main(String[] args) 
    { 
     Test m=new Test(); 
     System.out.println(m.temp()); 
     } 

} 

因为Integer can hold null value , primitive int cannot.

0

,则必须抛出NullPointerException

,因为在此声明,它会永远返回null return(true ? null : 0);;

2

任何人都可以解释此代码的输出?

这将始终通过NullPointerException。试图取消箱nullintNullPointerException

return(true ? null : 0); 

的条件始终true并且因此返回表达式求null。第二个和第三个操作数分别是null0。由于null可以是参考值,因此整个表达式将输入为Integer,因为它与0null最接近。由于返回类型是基本类型int,因此Integer null应参考拆箱到int,而这样做,它应该抛出NPEint不能抱null,但Integer即可。

请参阅JLS

类型的条件表达式的确定如下:

  1. 如果第二和第三个操作数中的一个是原始类型T的,并且其他的类型是施加拳击的结果转换(§5.1.7)为T,那么条件表达式的类型为T.

  2. 如果第二个和第三个操作数中的一个是空类型,而另一个的类型是引用类型,则条件表达式的类型是该引用类型。

0

一个NullPointerException异常将被抛出。这是因为三元将评估为包含null的盒装类型,并且当您对包含null的盒装类型(Java必须执行以返回int)进行取消装箱时,您会得到该异常。

欲了解更多详情,请参阅Conversion from null to int possible?

6

让我们这一个接一个:

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

int getIntValue(){ 

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

} 

这里取消装箱发生,你看到这个代码编译正确。即使这个代码运行良好。

现在来到你的代码:

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

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

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

int i =(int)null; 

而上面的代码基本上是给你的NullPointerException。

+0

+1,那是正确的,原始int不能保持null但Integer类可以,这就是为什么它会抛出NPE – anshulkatta