Search code examples
javamathvariable-assignment

Why does i = i + i give me 0?


I have a simple program:

public class Mathz {
    static int i = 1;
    public static void main(String[] args) {    
        while (true){
            i = i + i;
            System.out.println(i);
        }
    }
}

When I run this program, all I see is 0 for i in my output. I would have expected the first time round we would have i = 1 + 1, followed by i = 2 + 2, followed by i = 4 + 4 etc.

Is this due to the fact that as soon as we try to re-declare i on the left hand-side, its value gets reset to 0?

If anyone can point me into the finer details of this that would be great.

Change the int to long and it seems to be printing numbers as expected. I'm surprised at how fast it hits the max 32-bit value!


Solution

  • The issue is due to integer overflow.

    In 32-bit twos-complement arithmetic:

    i does indeed start out having power-of-two values, but then overflow behaviors start once you get to 230:

    230 + 230 = -231

    -231 + -231 = 0

    ...in int arithmetic, since it's essentially arithmetic mod 2^32.