Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The only <code>int</code> value for which it works is <code>Integer.MIN_VALUE</code>.</p> <p>It's because integers are negated using the <a href="http://en.wikipedia.org/wiki/Two%27s_complement" rel="nofollow">two's complement way</a>.</p> <p>Using</p> <pre><code>System.out.println(Integer.toBinaryString(Integer.MIN_VALUE)); </code></pre> <p>you see that <code>Integer.MIN_VALUE</code> is</p> <pre><code>10000000000000000000000000000000 </code></pre> <p>Taking the negative value is done by first swapping <code>0</code> and <code>1</code>, which gives</p> <pre><code>01111111111111111111111111111111 </code></pre> <p>and by adding <code>1</code>, which gives</p> <pre><code>10000000000000000000000000000000 </code></pre> <p>As you can see in the link I gave, Wikipedia mentions the problem with the most negative numbers and specifies it's the sole exception :</p> <blockquote> <p>The most negative number in two's complement is sometimes called "the weird number," because it is the only exception.</p> </blockquote> <p>Of course you have the same phenomenon for <code>Long.Min_Value</code> if you store it in a <code>long</code> variable.</p> <p>Note that <strong>this is only due to choices that were made regarding the binary storage of ints in Java</strong>. Another (bad) solution could for example have been to negate by simply changing the most significant bit and letting the other bits unchanged, this would have avoided this problem with MIN_VALUE but would have made 2 different <code>0</code> values and complicated binary arithmetic (how would you have incremented for example ?).</p>
 

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