Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pre- and postincrement in Java

Tags:

java

I just wanted to create a little Java-Puzzle, but I puzzled myself. One part of the puzzle is:

What does the following piece of code do:

public class test {
    public static void main(String[] args) {
        int i = 1;
        i += ++i + i++ + ++i;

        System.out.println("i = " + i);
    }
}

It outputs 9.

My (at least partly) wrong explanation:

I'm not quite sure, but I think the term after i += gets evaluated like this:

enter image description here

So

int i = 1;
i += ++i + i++ + ++i;

is the same as

int i = 1;
i += ((++i) + (i++)) + (++i);

This gets evaluated from left to right (See Pre and postincrement java evaluation).

The first ++i increments i to 2 and returns 2. So you have:

i = 2;
i += (2 + (i++)) + (++i);

The i++ returns 2, as it is the new value of i, and increments i to 3:

i = 3;
i += (2 + 2) + ++i;

The second ++i increments i to 4 and returns 4:

i = 4;
i += (2 + 2) + 4;

So you end up with 12, not 9.

Where is the error in my explanation? What would be a correct explanation?

like image 674
Martin Thoma Avatar asked Jul 11 '12 11:07

Martin Thoma


2 Answers

i += ++i + i++ + ++i; is the same as i = i + ++i + i++ + ++i;

The right-hand side is calculated from left-to-right, yielding i = 1 + 2 + 2 + 4; (which yields i = 9).

like image 180
Zéychin Avatar answered Sep 20 '22 20:09

Zéychin


The output is 9 (try it)

int i = 1;
i += ++i + i++ + ++i;

becomes

i = 1 + 2 + 2 + 4
like image 28
dash1e Avatar answered Sep 20 '22 20:09

dash1e