0

I want to know how the following code produces "-1" output.

 class Demo1
 {
  public static void main(String[] arg)
  {
     int i,j;
     for(i=-2,j=2;i++>0;j--)
     {
               i=++i;   
     }
     System.out.print(i); 
  }
 }

This above code produces output "-1", but how? Can anyone explain it? Thank you in advance!

Nisarg
  • 63
  • 1
  • 3
  • 8
  • 1
    Possible duplicate of [Difference between i++ and ++i in a loop?](http://stackoverflow.com/questions/484462/difference-between-i-and-i-in-a-loop) – Minhas Kamal Mar 23 '16 at 03:02

5 Answers5

1

i starts with -2. You check if i++ is greater then 0. This results in false since -2<0. The postincrement in your condition for the for loop produces the value i = -2 + 1 afterwards,

SomeJavaGuy
  • 7,307
  • 2
  • 21
  • 33
1

In your for loop for(i=-2,j=2;i++>0;j--) i will get incremented first before the comparison, at that moment i is -1 and since it's not > 0 it's exiting the loop.

Let'sRefactor
  • 3,303
  • 4
  • 27
  • 43
1

your answer is because of for loop you have written. your flow does not go inside for loop. initial value of variable i is -2 and j is 2 , your condition for "for loop" is - i should be greater than 0(since its post increment) and here your code is not getting inside "for loop",since value in i is -2 and then post increment(i++) happens and value of i becomes -1 and it prints so. for more details , you can read pre & post increment

NikhilP
  • 1,508
  • 14
  • 23
0
  1. i=-2; Since i++>0 is false (because -2<0) it exits the loop.
  2. Now i is post-incremented to -1.
  3. The print statement now prints the value of i which is -1.
Anindya Dutta
  • 1,972
  • 2
  • 18
  • 33
0

Nothing to do with operator precedence.

No matter in which order the operators in i++>0 are performed the result is always the same: As you start with i = -2, result will be false and value of i will be -1

Jan
  • 13,738
  • 3
  • 30
  • 55