4

From java documentation int has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

I have a class Test.java.

public class Test
{
    public static void main(String[] args)
    {
        int i=2147483647; //max positive value an int can store
        for(;;)
        {
            System.out.println(++i);
        }
    }
}

As per my knowledge ++i should increment the value of i by 1 and throw exception, because 2147483648 is not allowed in int.

But when I run above program it goes running(because of infinite loop), and instead of incrementing the value to 2147483648, the value assigned to i is -2147483648, And values is decremented each time by 1.

Sample run (after modifying class)

public static void main(String[] args)
{
    int i=2147483647;
    for(;;)
    {
        System.out.println(++i);
        System.out.println(++i);
        System.out.println(++i);
        System.out.println(++i);
        System.out.println(++i);
        break;
    }
}

Output:

-2147483648
-2147483647
-2147483646
-2147483645
-2147483644

Answers/Hints will be appreciated.

Bhushan
  • 6,151
  • 13
  • 58
  • 91

5 Answers5

13

As per my knowledge ++i should increment the value of i by 1 and throw exception, because 2147483648 is not allowed in int.

Your understanding is incorrect. Integer arithmetic overflows silently in Java.

From section 15.18.2 of the JLS:

If an integer addition overflows, then the result is the low-order bits of the mathematical sum as represented in some sufficiently large two's-complement format. If overflow occurs, then the sign of the result is not the same as the sign of the mathematical sum of the two operand values.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
4

You've encountered a situation known as integer overflow: http://en.wikipedia.org/wiki/Integer_overflow

Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

This is known as integer overflow. Arithmetic operations on integer values never throw an exception, and this is not a Java-only thing.

The minimum and maximum values only serves you to decide if an int is or is not enough for your computation.

Raffaele
  • 20,627
  • 6
  • 47
  • 86
2

I won't give the exact answer, but consider this:

  • how is an integer represented in Java(in what kind of binair number representation)?
  • what happens if you add 1 to the highest possible binair number?
Tom
  • 133
  • 6
2

In java underflow and overflow of numeric values are off(silent). During underflow and overflow event Java keeps continuing incrementing/decrementing for numeric value's range.

Section 4.2.2. Integer Operations

The integer operators do not indicate overflow or underflow in any way.

Alpesh Gediya
  • 3,706
  • 1
  • 25
  • 38