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?
i<=j && j<=i && i!=jthis condition always evaluates to true. Just take a piece of paper and evaluate you will catch it :)iorj, when would you expect the loop to terminate?i<=jandj<=iyou can conclude, thati == j, which contradicts the last term. Thus the whole expression evaluates to false and the while would not be entered. Key point is the object identity here!