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.