-2

I am new to java. Wanted help to analyse small bit of code as below. Below code prints value of 'i' as 0 always. It seems like 'i' never gets incremented and below for loop results in infinite loop. Can some one explain why 'i' is not getting incremented at all? I know when a post increment operator is used, the expression value is first used and then the value gets incremented. So, first iteration of the loop will print value of 'i' as 0. But, at least in second iteration, 'i' should have been incremented to 1 and so on. Right?:

public class PostIncExample {

    public static void main(String[] args) {
        for(int i=0; i<10;){
            System.out.println(i);
            i=i++;
            System.out.println("hi" + i);
        }

    }

}
Sathish D
  • 4,854
  • 31
  • 44

2 Answers2

2

In your code, i++ returns the "old" value of i (the value it had before incrementing it). This old value is then assigned to i. So after i = i++, i has the same value as before.

Grodriguez
  • 21,501
  • 10
  • 63
  • 107
1
++i increments and then uses the variable.
i++ uses and then increments the variable.

Thats why above code always print 0 and goes infinite

You can modify your code as below :

public class PostIncExample {
    public static void main(String[] args) {
        for(int i=0; i<10;){
            System.out.println(i);
            i=++i;
            System.out.println("hi" + i);
        }
    }
}

PRE-increment is used when you want to use the incremented value of the variable in that expression.

POST-increment uses the original value before incrementing it.

Community
  • 1
  • 1
Shiladittya Chakraborty
  • 4,270
  • 8
  • 45
  • 94