我已经写了一段Java代码,它在无限循环中运行。
代码如下:
public class TestProgram {
public static void main(String[] args){
Integer i = new Integer(0);
Integer j = new Integer(0);
while(i<=j && j<=i && i!=j){
System.out.println(i);
}
}
}
在上面的代码中,虽然看到了while
循环中的条件,但乍一看该程序似乎不会进入while
循环。但实际上它是一个无限循环,并不断打印数值。
这是怎么回事?
发布于 2013-09-15 01:45:19
发布于 2014-02-24 03:20:59
我们首先要了解两种不同的情况,
案例1:
Integer i = new Integer(10);
Integer j = new Integer(10);
System.out.println((i<=j && j<=i && i!=j));
System.out.println(i!=j);
案例2:
Integer i = 10;
Integer j = 10;
System.out.println((i<=j && j<=i && i==j));
System.out.println(i==j);
两者都是不同的,因为
在情况1中:i!=j
将为true
,因为两者都引用了堆中的两个不同的对象,并且不能相同。但
在情况2中:i==j
将是true
,因为这两个10都是整数字面值,并且Java维护pool for Integer literals
,它的值为(-128 <= X <= 127)
。因此,在本例中,10<=127结果为真,因此两者都将引用相同的对象。
发布于 2013-09-15 01:46:12
循环没有结束,因为您的条件为真(i != j为真,因为有两个不同的对象,请改用Integer.valueOf ),并且循环内部的值不会改变,因此您的条件永远保持为真。
https://stackoverflow.com/questions/18804599
复制相似问题