Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>No, they are NOT equivalent the way you expressed them.</p> <pre><code>short x = 0, y = 0; x -= y; // This compiles fine! x = x - y; // This doesn't compile!!! // "Type mismatch: cannot convert from int to short" </code></pre> <p>The problem with the third line is that <code>-</code> performs what is called "numeric promotion" (<a href="http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.6" rel="nofollow noreferrer">JLS 5.6</a>) of the <code>short</code> operands, and results in an <code>int</code> value, which cannot simply be assigned to a <code>short</code> without a cast. <em>Compound assignment operators contain a hidden cast!</em></p> <p>The exact equivalence is laid out in <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.26.2" rel="nofollow noreferrer">JLS 15.26.2 Compound Assignment Operators</a>:</p> <blockquote> <p>A compound assignment expression of the form <em>E1 op= E2</em> is equivalent to <em>E1 = (T)((E1) op (E2))</em>, where <em>T</em> is the type of <em>E1</em>, except that <em>E1</em> is evaluated only once.</p> </blockquote> <p>So to clarify some of the subtleties:</p> <ul> <li>Compound assignment expression doesn't reorder the operands <ul> <li>Left hand side stays on the left, right hand side stays on the right</li> </ul></li> <li>Both operands are fully-parenthesized to ensure <em>op</em> has the lowest precedence <ul> <li><code>int x = 5; x *= 2 + 1; // x == 15, not 11</code></li> </ul></li> <li>There is a hidden cast <ul> <li><code>int i = 0; i += 3.14159; // this compiles fine!</code></li> </ul></li> <li>The left hand side is only evaluated once <ul> <li><code>arr[i++] += 5; // this only increments i once</code></li> </ul></li> </ul> <p>Java also has <code>*=</code>, <code>/=</code>, <code>%=</code>, <code>+=</code>, <code>-=</code>, <code>&lt;&lt;=</code>, <code>&gt;&gt;=</code>, <code>&gt;&gt;&gt;=</code>, <code>&amp;=</code>, <code>^=</code> and <code>|=</code>. The last 3 are also defined for booleans (<a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.22.2" rel="nofollow noreferrer">JLS 15.22.2 Boolean Logical Operators</a>).</p> <h3>Related questions</h3> <ul> <li><a href="https://stackoverflow.com/questions/2696812/varying-behavior-for-possible-loss-of-precision/">Varying behavior for possible loss of precision</a></li> <li><a href="https://stackoverflow.com/questions/2324549/why-doesnt-java-have-compound-assignment-versions-of-the-conditional-and-and-con">Why doesn’t Java have compound assignment versions of the conditional-and and conditional-or operators? (&amp;&amp;=, ||=)</a></li> </ul>
 

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