I'll show you a C # code:
using static System.Console;
public class Program {
public static void Main() {
for (int i = 1; i >= 0; i *= 2) { WriteLine($"i: {i}"); }
checked {
for (int j = 1; j >= 0; j *= 2) { WriteLine($"j: {j}"); }
}
}
}
See running on .NET Fiddle . And in Coding Ground . Also put it in GitHub for future reference .
I do not do with Java because it can not control the overflow check.
By default it is turned off, so when you arrive at a value above the capacity that the int
type supports it continues to operate normally only that there is a signal exchange that is a bit in the number. As a matter of performance it is not checked if this occurs. Being negative, the loop terminates.
The second I did bind the check, slows down because every change of the variable has to see if it did not break, but then an error ends up occurring because the processor indicates that the operation is invalid and .NET captures it and information the implementation.
But you can see Java too . I changed to multiply by 2 to get into geometric progression and quit more quickly. It could also have started with a larger number.
The maximum size of int
is 2,147,483,647 (2 raised to 31 since it has 32 bits and one of them is used as a signal). The minimum value is -2,147,483,648.
So it goes into loop infinity:
class Loop {
public static void main(String[] a) {
int cont = 0;
for (int i = 1; i < 10000000000000000L; i *= 2, cont++) { System.out.println("i:" + i); }
System.out.println("cont:"+cont);
}
}
See working on ideone .