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.
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.
See more on this question at Stackoverflow