Multiplication Integer.MAX_VALUE in Java

I just played Java. Wrote this small program:

public class MaxValue{
    public static void main(String[] args){
        int i  =  Integer.MAX_VALUE;
        for(int j = 1; j<=10;j++){
            System.out.println(i*j);
        }
    }
}

The output is as follows:

2147483647

-2

2147483645

-4

2147483643

-6

2147483641

-8

2147483639

-10

Now I was surprised. I do not know how to explain this result. I know that I can use long instead to process values ​​greater than the maximum limit of an integer. However, I'm only interested in knowing how java calculates this?

+5
source share
3 answers

We need to analyze the binary content of the result:

Integer.MAX_VALUE * 1 = 0x7fffffff, which is decimal 2147483647

Integer.MAX_VALUE * 2 = 0xfffffffe, which is -2

Integer.MAX_VALUE * 3 = 0x17ffffffd, but it is 33 bits, after truncation it is 0x7ffffffd, which is 2147483645

etc.

+1

, , overflow, java : - Integers.MAX_VALUE Integer.MIN_VALUE,

0

It is called overflow. Since you are working on the highest possible value, any mathematical increase operation may end up in overflow.

Additional information on Java overflows: http://javapapers.com/core-java/java-overflow-and-underflow/

0
source

All Articles