Kameron
Kameron

Reputation: 733

Complicated Expression Java

 public class I {
        public static void main(String  args[])
        {
            int i=0,j=1,k=2;
            i=i++ - --j + ++k;
            System.out.println("\ni : "+i+"\nj : "+j+"\nk : "+k);
        }
    }

Can anyone please explain to me Why the above code gives output :

i : 3
j : 0
k : 3

Instead of giving the output :

i : 4
j : 0
k : 3

?

Upvotes: 0

Views: 182

Answers (6)

Eugene Retunsky
Eugene Retunsky

Reputation: 13139

  1. i++ - gives 0 (and increments i)
  2. --j decrements and gives 0
  3. ++k increments and gives 3
  4. the result of 0 + 0 + 3 is assigned to i (which overwrites i's value 1).

Therefore: i : 3.

Upvotes: 3

talnicolas
talnicolas

Reputation: 14053

The value of i is 3 because the expression is evaluated like that:

 i++ //still equals 0 since it's incremented after the evaluation
 -
 --j // equals 0 too since it's decremented is done before the evaluation
 +
 ++k // equals 3 since it's incremented before the evaluation

Upvotes: 1

fsaftoiu
fsaftoiu

Reputation: 375

  1. i++ gives 0 and then i becomes 1
  2. --j makes j become 0 and then gives 0, plus 0 from step 1 gives 0
  3. ++k makes k become 3 and then gives 3, plus 0 from step 2 gives 3, which is stored into i

Hence, i is 3, j is 0 and k is 3.

Upvotes: 1

TM.
TM.

Reputation: 111027

This is because of the difference between post increment and pre increment operators.

Pre increment comes before the variable (e.g. ++i) and post increment comes after the variable (e.g. i++).

Break it down into smaller parts:

i++   // post increment means increment AFTER we evaluate it
      // expression evaluates to 0, then increment i by 1

--j   // pre decrement means decrement BEFORE evaluation
      // j becomes 0, expression evaluates to 0

++k   // pre increment means increment BEFORE evaluation
      // k becomes 3, expression evaluates to 3

So now we have:

i = 0 - 0 + 3   // even though i was set to 1, we reassign it here, so it's now 3

Upvotes: 1

Ruan Mendes
Ruan Mendes

Reputation: 92274

Here's what the line in question produces, Remember that if i is 0, then i++ == 0 and ++i == 1

i = i++ - --j + ++k;
i = (0) - (-0) + (3) // i is 3

Upvotes: 1

Paul Bellora
Paul Bellora

Reputation: 55213

I'm guessing your confusion hinges on the use of i++ - but the side effect of i++ incrementing i has no effect, since i is reassigned the result of the "complicated expression".

Upvotes: 1

Related Questions