7

I was just playing around in 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 got surprised. I do not know how to explain this output. I know I can use long instead for handling values more than the max limit of integer. However I am only interested to know how java calculates the this?

thelastray
  • 472
  • 2
  • 9
  • 21

3 Answers3

3

We need to analize 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

and so on...

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275
2

It is called an overflow. Since you are operating over the maximum possible value, any mathematical increasing operation can potentially end up in an overflow.

More info about overflows in Java: http://javapapers.com/core-java/java-overflow-and-underflow/

Gothmog
  • 871
  • 1
  • 8
  • 20
1

What you are experiencing is called overflow, with primitive type java will handle this in the following way : - On reaching the Integers.MAX_VALUE it will just go to the Integer.MIN_VALUE and this way you just get a negative value

tmwanik
  • 1,643
  • 14
  • 20