Integer i = new Integer(0);
Integer j = new Integer(0);
while(i <= j && j <= i && i !=j ){
System.out.println(i);
}
Why does this while loop execute?
I understand that i != j
. But separately, both i <= j
and j <= i
returns true. Why? And doesn't that mean that i == j
? In that case the while loop shouldn't execute even once. But it goes for an infinite loop. Why is this so?
While ==
can be performed between two references (and is, when both sides are Integer
), <=
can't - so the compiler unboxes. So, your code is equivalent to:
while (i.intValue() <= j.intValue() &&
j.intValue() <= i.intValue() &&
i != j)
Now when i
and j
refer to different Integer
objects with the same value, all of those conditions will be met - hence the loop keeps executing.
See more on this question at Stackoverflow