欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

java三元运算符的bug?? 博客分类: Java javaJDK三元运算符 

程序员文章站 2024-03-20 18:33:10
...

以前没有注意到问题,下面的TestCase运行报空指针异常。

 

 

public class A extends TestCase {

	public void testA() {
		Integer num = null;
		assertNull(false ? Integer.valueOf(0) : num);
		assertNull(false ? 0 : num);
	}
}
 

 

class文件分析:

 

 

false ? Integer.valueOf(0) : num

 

public void testA();
  Code:
   Stack=1, Locals=3, Args_size=1
   0:   aconst_null
   1:   astore_1
   2:   aload_1
   3:   astore_2
   4:   return

 

vs

 

false ? 0 : num

 

public void testA();
  Code:
   Stack=1, Locals=3, Args_size=1
   0:   aconst_null
   1:   astore_1
   2:   aload_1
   3:   invokevirtual   #15; //Method java/lang/Integer.intValue:()I
   6:   invokestatic    #21; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
   9:   astore_2
   10:  return

 

总结:由于三元运算符导致,由于num为null,转为int时会出错。这算不算JDK6的bug?