Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the For-loop does not terminates?

Tags:

java

for-loop

Consider the below code:

public class Test {
     public static void main(String args[]) {
      long startTime = System.nanoTime();
      for(int i = 1; i > 0; i++) {
       System.out.println(i);
      }
      System.out.println(System.nanoTime() - startTime);  
     }
}

Output:

1
2
3
4
5
.
.
.
2147483643
2147483644
2147483645
2147483646
2147483647
16825610038948

I'm not able to get the value of startTime from Eclipse console, since there are huge amount of lines.

We call the above For-Loop as an Infinite Loop since i value is always greater than zero. Theoretically, the loop should not terminate. But since we use int, whose maximum value is 2147483647, the For-Loop terminates when we increment i, i.e. i++, when i = 2147483647.

So I was assuming that, when we increment i when i = 2147483647, the value of i will become negative or zero, so the condition becomes false, and the For-Loop terminates.

So to confirm, I tried the below code:

int i = 2147483647; // Maximum value of int
System.out.println(i++);

So if my assumption is correct, it should have printed any negative number or a zero value. but instead I got the following output:

2147483647

Here is my question/doubt:

When we increment i value, when i = 2147483647, the value of i is still the same, i.e. 2147483647. So how does the For-loop, in the above scenario, terminated without any error or exception?

like image 646
Lenn Kenn Avatar asked Dec 11 '22 10:12

Lenn Kenn


2 Answers

It should've been ++i in your System.out.println();.

System.out.println(++i);

Your assumption is correct, when we increment i, when i = 2147483647, i becomes -2147483648.

like image 100
Gokul Nath KP Avatar answered Dec 14 '22 00:12

Gokul Nath KP


i++ is different from ++i. First is a post-increment while second is a pre-increment.

i++ means

use the current value of i for the expression, then increment it

while the other, which is the one you are looking for, means:

increment the value of i by 1, then use it in the expression

like image 32
Jack Avatar answered Dec 13 '22 22:12

Jack