[英]returning null through conditional operator when return value is int
谁能解释这段代码的输出?
public class Main
{
int temp()
{
return(true ? null : 0);
}
public static void main(String[] args)
{
Main m=new Main();
System.out.println(m.temp());
}
}
让我们一一介绍:
第一次编译:为什么编译成功? 看看下面的代码:
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是第一个包装器(自动装箱)到Integer,然后返回类型基本上转换为Integer类型(请记住,我们可以在此处传递null)。 现在,当您传递null作为返回类型时,在运行时将其转换为int泛型类型。
因此,我们基本上要做的如下:
int i =(int)null;
上面的代码基本上为您提供了nullpointerexception。
谁能解释这段代码的输出?
这将始终通过NullPointerException
。 尝试将null
取消包装为int
是NullPointerException
。
return(true ? null : 0);
条件始终为true
,因此返回表达式的值为null
。 第二和第三操作数分别为null
和0
。 由于null
可以是引用的值,因此整个表达式将被键入Integer
因为它与0
和null
最接近。 由于返回类型是原始int
,因此应该将Integer null
引用取消装箱到int
,同时这样做应该抛出NPE
因为int
不能容纳null
,而Integer
可以。
请参阅JLS 。
条件表达式的类型确定如下:
如果第二个操作数和第三个操作数之一是原始类型T,而另一个操作数的类型是对T应用装箱转换(第5.1.7节)的结果,则条件表达式的类型为T。
如果第二个操作数和第三个操作数之一为空类型,而另一个操作数的类型为引用类型,则条件表达式的类型为该引用类型。
它应该抛出NullPointerException
因为return(true ? null : 0);
在此语句中,它将始终返回null;
将抛出NullPointerException。 这是因为三元数将求值为包含null的装箱类型,并且当您对包含null的装箱类型开箱(Java必须这样做以返回int)时,您会得到该异常。
有关更多详细信息,请参见可能从null转换为int吗?
这将是NullPointerException
,因为不能将int分配为null
但是,此代码将始终返回null,因为在这里您将条件始终声明为true
,因此将返回三元语句的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.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.