Java – 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.

Below is the code:

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

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.

What is happening here?

Best Answer

  • 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 is evaluated to true because of the above reason.

  • 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.

All the conditions are true, and you are not changing i and j in loop, so it is running infinitely.