Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The operator += is an addition assignment operator. Like Alya said above, <code>x += x++</code> is equivalent to <code>x = x + x++</code>, which in your case is <code>x = 10 + 10</code>. However, it's a very messy statement and I'll explain why towards the end of this post.</p> <p>Now, you're probably thinking "Why is it 20 and not 21 (10 + 11) since you have the ++?" and that's valid. There's actually a difference between a post-increment and a pre-increment. x++ is the post-increment and will actually evaluate the value of x first and THEN increment x, while ++x is the pre-increment which will increment x and THEN evaluate the value of x.</p> <p>For example, <code>x = 10; System.out.println(x++); System.out.println(x);</code> will print 10 and then print 11 because the first print line prints <code>x</code> and THEN performs the ++ calculation, making <code>x</code> 11 which the next line prints. Conversely, <code>x = 10; System.out.println(++x); System.out.println(x);</code> will print 11 on both print statements.</p> <p>Going back to why I said <code>x += x++;</code> is very messy is because technically the ++ operator isn't performed in this case. <code>x++</code> is technically the same as <code>x=x+1</code> and remembering that x+=y is the same as x = x+y) , the line <code>x += x++;</code> is kind of like saying <code>x = x + (x = x + 1);</code> which is kind of weird looking because you do 2 assignment statements in one and won't actually "work how you want it". Back to your example <code>int x = 10; x += x++;</code> if you print x, you will get 20 even though you could look at it as: x is now the value of x + the value of x, then finally + 1 to it. But unfortunately, that's not how it works.</p> <p>To solve your problem, if you change your code from a post-increment to a pre-increment, then it should work, ie: <code>x+=++x;</code> will print your 11 but I would argue the that's quite unreadable and a bit confusing. <code>x+=x; x++; System.out.println(x);</code> is easier to follow.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload