Search code examples
javaintegerinteger-arithmetic

Why is the result of my int multiplication wrong?


I have the the following code where the results exceeds the limit an integer type variable can store and need to understand why I am getting this result (268,435,456=2^28)

public static void main(String[] args) {
int x = 16+256;
for( int i =0; i<6; i++) {
            x*=16;
        }
        System.out.println(x);
}
}

Solution

  • Consider how this looks with all the values expressed in binary.

    Initially, x = 00000000000000000000000100010000. Then every time you multiply by 16, you add 4 zeroes to the right, and remove 4 digits from the left.

    So you get results like

    00000000000000000001000100000000
    00000000000000010001000000000000
    

    and so on. But once you've done this 6 times, the first 1 disappears off the left end of the number - this is the integer overflow. So you're left with

    00010000000000000000000000000000
    

    which is 2 to the 28.