Pre- and postincrement in Java
<p>I just wanted to create a little Java-Puzzle, but I puzzled myself. One part of the puzzle is:</p>

<p>What does the following piece of code do:</p>

<pre class="lang-java prettyprint-override"><code>public class test {
    public static void main(String[] args) {
        int i = 1;
        i += ++i + i++ + ++i;

        System.out.println("i = " + i);
    }
}
</code></pre>

<p>It outputs <code>9</code>. </p>

<p><strong>My (at least partly) wrong explanation</strong>:</p>

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

<p><img src="http://i.stack.imgur.com/P6tx2.gif" alt="enter image description here"></p>

<p>So</p>

<pre><code>int i = 1;
i += ++i + i++ + ++i;
</code></pre>

<p>is the same as</p>

<pre><code>int i = 1;
i += ((++i) + (i++)) + (++i);
</code></pre>

<p>This gets evaluated from left to right (See <a href="http://stackoverflow.com/q/4203418/562769">Pre and postincrement java evaluation</a>).</p>

<p>The first <code>++i</code> increments <code>i</code> to <code>2</code> and returns <code>2</code>. So you have:</p>

<pre><code>i = 2;
i += (2 + (i++)) + (++i);
</code></pre>

<p>The <code>i++</code> returns <code>2</code>, as it is the new value of <code>i</code>, and increments <code>i</code> to <code>3</code>:</p>

<pre><code>i = 3;
i += (2 + 2) + ++i;
</code></pre>

<p>The second <code>++i</code> increments <code>i</code> to <code>4</code> and returns <code>4</code>:</p>

<pre><code>i = 4;
i += (2 + 2) + 4;
</code></pre>

<p>So you end up with <code>12</code>, not <code>9</code>. </p>

<p><strong>Where is the error in my explanation? What would be a correct explanation?</strong></p>
