1
int maxAgain = 2147483647+1;
System.out.println(maxAgain);
int maxAgain1 =  2147483648
System.out.println(maxAgain1);

why maxAgain and maxAgain1 has difference.

NOTE:

  • maximum value of integer: 2147483647
  • minimum value of integer: -2147483648

here maxAgain run successfully and maxAgain1 gives error.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • The first one works because it overflows and results in the next value, which in this case is -2147483648 but the second one is not allowed because you can't assign a value to int which is not in the allowed range. – Orell Buehler Mar 03 '21 at 07:20

3 Answers3

2

Because the integer overflows. When it overflows, the next value is Integer.MIN_VALUE. Whenever you add 1 to the largest java Integer, which has a bit sign of 0, then its bit sign becomes 1 and the number becomes negative.

In short, it's the same reason why the date changes when you cross the international date line: there's a discontinuity there. It's built into the nature of binary addition.

Sources:

1 2 3

Spectric
  • 30,714
  • 6
  • 20
  • 43
1

Your first line overflowed, with a result of -2147483648, as seen running on IdeOne.com. This is explained in the correct Answer by Spectric.

Math.addExact

To be notified at runtime of such an Overflow happening, use static method Math.addExact. If your addition causes integer overflow, an exception is thrown, ArithmeticException.

        try
        {
              int result = Math.addExact( 2_147_483_647 , 1 ) ;
              System.out.println( result ) ;
        }
        catch ( ArithmeticException e )
        {
             System.out.println( e ) ;
        }

See that code run live at IdeOne.com.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
0

An integer is capable of storing any number between and including -2147483648 to 2147483647 because it is designated 32 bits of storage.

You can use the long type instead, which can store -9,223,372,036,854,775,808 to 223,372,036,854,775,807, and 64 bits.

ublec
  • 172
  • 2
  • 15