Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does (i<=j && j<=i && i!=j) evaluate to TRUE?

Tags:

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?

like image 302
Kshitij Jain Avatar asked Sep 14 '13 17:09

Kshitij Jain


People also ask

Why do we use J and i?

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.

Why only i and J are used in loops?

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.

What does i and j mean in coding?

i=iteration while j=after interation.

What is i and J in Java?

Answer: i and j are nothing but loop variables . They are used to iterate the loops .


2 Answers

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

like image 85
Juned Ahsan Avatar answered Sep 18 '22 01:09

Juned Ahsan


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

like image 37
Ashwani Avatar answered Sep 17 '22 01:09

Ashwani