(i<=j && j<=i && i!=j) Why is true a return when calculated?

Asked 2 years ago, Updated 2 years ago, 19 views

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);
        }
    }
}

There's a code like this. In that code, I thought the println syntax in while wouldn't work I'm in an infinite loop. Why is that true?

java

2022-09-21 18:12

1 Answers

i<=j is auto unboxing and returns true because it is 0<=0. j<=i returns true for the same reason.

An operation of == or != on an object is an operation that compares whether two objects reference the same object. In i!=j, i and j are true because they created different objects. So the above operation becomes true and it keeps returning true and falls into an infinite loop.


2022-09-21 18:12

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.