为什么(i< = j& j< = i& i!= j)评估为TRUE? [英] Why does (i<=j && j<=i && i!=j) evaluate to TRUE?
问题描述
我已经编写了一段无限循环运行的Java代码.
I have written a piece of Java code which is running in an infinite loop.
下面是代码:
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
循环中.但是实际上这是一个无限循环,并不断显示该值.
In the code above, while seeing the condition in the while
loop, at first it looks like that program will not go inside the while
loop. But actually it is an infinite loop and keeps printing the value.
这是怎么回事?
推荐答案
-
i< = j
的评估结果为true
,因为int会自动取消装箱比较,然后i
和j
都保留默认值0
.i <= j
is evaluated totrue
, because auto unboxing happens for int comparisons and then bothi
andj
hold the default value,0
.j< = i
被评估为true
.i!= j
被评估为true
,因为i
和j
都是不同的对象.并且在比较对象时,没有任何必要自动拆箱.i != j
is evaluated totrue
, because bothi
andj
are different objects. And while comparing objects, there isn't any need of auto unboxing.所有条件都为真,并且您没有循环更改
i
和j
,因此它无限运行.All the conditions are true, and you are not changing
i
andj
in loop, so it is running infinitely.这篇关于为什么(i< = j& j< = i& i!= j)评估为TRUE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!