!= operator in Java for loop

Viewed 632

How come the below code prints "The value of J is: 1000"?
I would've thought that the "j != 1000" would evaluate to false in all instances (Because 1000 mod 19 is not 0), hence making it an infinite loop.

public static void loop2() {
    int j = 0;

    for(int i=0;j != 1000;i++) {
        j = j+19;
    }
    System.out.println("The value of J is: " + j);
}
4 Answers

Max value of int in java is 2,147,483,647 on adding 19 to j, again and again, this value will be passed. After which it will start again from min value of int i.e. -2,147,483,648.

This will continue until the value of j become 1000 at some point. Hence, the loop will stop.

j will iterate 17 times over the max value of the integer to reach this point. Code for checking:

public class Solution {
    public static void main(String args[]) {
        int j = 0;
        int iterationCount = 0;

        for(int i=0;j != 1000;i++) {
            j = j+19;
            if(j - 19 > 0 && j < 0) {
                iterationCount ++;
            }

        }
        System.out.println("The value of J is: " + j + " iterationCount: " + iterationCount);
    }
}

Output:

The value of J is: 1000 iterationCount: 17

Scanning for overflows like this:

public static void main(String[] args) {
  int j = 0;
  for(int i=0;j != 1000;i++) {
    j = j+19;
    if(j < Integer.MIN_VALUE+19){
      System.out.println("overflow");
    }
  }
  System.out.println("The value of J is: " + j);
}

prints

overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
overflow
The value of J is: 1000

meaning the j overflows 17 times until the increment by 19 finally hits 1000.

This is, as Saheb stated, due to the integer overflow.

The value of J, 1000, is reached after 3842865528 iterations

public static void loop2()
{
    int j = 0;
    long iterations = 0;

    for (int i = 0; j != 1000; i++) {
        j = j + 19;
        iterations++;
    }
    System.out.println("The value of J is: " + j + " reached after " + iterations + " iterations");
}

you defined your j as int. Integers have a defined range. The Max-Value of the signed Integer is 2,147,483,647. As soon as you go over that value you have a bit-overflow which causes the whole thing to start at the min value. In case of Integers thats -2,147,483,648. At some point in the loop you get to a negativ starting value of the loop which leads your loop to land at 981+19 = 1000 >>> loop is exited, cause J equals your exit-condition of your for-loop.

Related