Lenn Kenn
Lenn Kenn

Reputation: 51

Why the For-loop does not terminates?

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?

Upvotes: 4

Views: 316

Answers (4)

Dax Joshi
Dax Joshi

Reputation: 143

post increment i++ increments the value after sout executes. try ++i to see changed value.

Upvotes: 0

user2880879
user2880879

Reputation: 297

Following code will clarify more about ++i and i++

    int i = 0
    System.out.println(" before i++ " + i++);
    System.out.println(" after i++ " + i);
    i = 0;
    System.out.println(" before ++i " + ++i);
    System.out.println(" after ++i " + i);

Prints

 before i++ 0
 after i++ 1
 before ++i 1
 after ++i 1

So

int i = 0;
int j = ++i;
i = 0;
int c = i++;

In this case value of j will be 1 and value of c = 0.

Upvotes: 1

Jack
Jack

Reputation: 133669

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

Upvotes: 2

Gokul Nath KP
Gokul Nath KP

Reputation: 15574

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.

Upvotes: 10

Related Questions