为什么(i< = j& j< = i& i!= j)评估为TRUE? [英] Why does (i<=j && j<=i && i!=j) evaluate to TRUE?

查看:69
本文介绍了为什么(i< = j& j< = i& i!= j)评估为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 to true, because auto unboxing happens for int comparisons and then both i and j hold the default value, 0.

      j< = i 被评估为 true .

      i!= j 被评估为 true ,因为 i j 都是不同的对象.并且在比较对象时,没有任何必要自动拆箱.

      i != j is evaluated to true, because both i and j 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 and j in loop, so it is running infinitely.

      这篇关于为什么(i&lt; = j&amp; j&lt; = i&amp; i!= j)评估为TRUE?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆