谁能解释这段代码的输出?
public class Main
{
int temp()
{
return(true ? null : 0);
}
public static void main(String[] args)
{
Main m=new Main();
System.out.println(m.temp());
}
}
谁能解释这段代码的输出?
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
. 试图拆箱null
是int
一个NullPointerException
.
return(true ? null : 0);
条件始终为true
,因此返回表达式的计算结果为null
。第二和第三个操作数分别是null
和0
。由于null
can 是一个引用的值,整个表达式将被键入到,Integer
因为它是最接近0
and的匹配项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.