Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

!= operator in Java for loop

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);
}
like image 765
Alex5207 Avatar asked Nov 30 '22 14:11

Alex5207


1 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
like image 167
Saheb Avatar answered Dec 04 '22 12:12

Saheb