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 and j are commonly used in linear algebra when doing matrix multiplication and summations. i is conveniently short for index . and j is lexicographically adjacent to i . Now that it's so established, I wouldn't use anything else, lest the programming gods bring pain upon ye.
Generally the i in for loops stands for iterator, that's why most of programmers use i instead of other names. i and j are just a variable name, you can use any variable name like a, b, c,x, y or number, length etc.
i=iteration while j=after interation.
Answer: i and j are nothing but loop variables . They are used to iterate the loops .
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.
Because you are comparing
0 < = 0 (true) // unboxing
0 > = 0 (true) // unboxing
reference != secondReference (true)
as you are creating objects, not a primitive comparison. So it evaluates to while(true) { // Never ending loop }
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With