getting hash values while trying to increment the value inside for loop in a java program

Viewed 23

I'm trying to get the output of 8 through this loop condition but I am getting this value instead:

-2147483648

class Test1 {
    public static void main(String [] args) {
        int p = 2; 
        int j=5; 
        for (int i = p; i < j; i++) {
            j++;
        }
        System.out.println(j);
    } 
}

Why is it happening and where do I need to look into?

1 Answers

In your loop, you're incrementing both i and j. That means that i < j is going to be true for several iterations.

Eventually, j reaches the largest possible int; which means that the next time you increment it, it will flip to the smallest possible int. Finally, it's less than i, so the loop will break. Therefore, the final value of j, at the end of your program, is the smallest possible int, which is -2147483648.

Related