I was trying to check different inputs and creating infinite loops in java and I found that once the int is getting incremented over the maximum limit it turns in to negative -2147482958. I am just increasing the int in infinite loop…
Code:
public static void infiniteLoop(){
for(int i=0;i>-1;i++){
i = i + 1000;
System.out.println(i);
}
}
The last to value gets printed out is,
2147483337
-2147482958
Now, Why does it goes to negative?
Because that is what is specified to happen in Java when an
intcalculation overflows.JLS 15.18.2
(This doesn’t explicitly say that overflow always gives a negative number. And it doesn’t always. But if you apply the rule, it does explain why incrementing
Integer.MAX_VALUEby+1gives youInteger.MIN_VALUE…)