title: Java automatic type promotions
body: <p>I quote from Herbert Schildt : JAVA, The Complete Reference 8th Edition.</p>
  
  <p>Chapter 4 : Operators</p>
  
  <p>Java’s automatic type promotions produce unexpected results when you are shifting <code>byte</code> and <code>short</code> values. As you know, <code>byte</code> and <code>short</code> values are promoted to <code>int</code> when an expression is evaluated. Furthermore, the result of such an expression is also an <code>int</code>. This means that the outcome of a <code>left shift</code> on a <code>byte</code> or <code>short</code> value will be an <code>int</code>, and the <code>bits</code> shifted <code>left</code> will not be lost until they shift past <code>bit</code> position <code>31</code>. </p>
  
  <p>Furthermore, a negative <code>byte</code> or <code>short</code> value will be <strong>sign-extended</strong> when it is promoted to <code>int</code>. Thus, the <strong>high-order bits</strong> will be filled with <code>1’s</code>. For these reasons, to perform a left shift on a byte or short implies that you must discard the high-order bytes of the int result. For example, if you left-shift a <code>byte</code> value, that value must first be promoted to <code>int</code> and then shifted. This means that you must discard the first <code>3 bytes</code> of the result if what you want is the result of a shifted byte value. The easiest way is to simply cast the result back into a <code>byte</code>.</p>
  
  <pre><code>    byte a = 64, b;
      int i;
      i = a &lt;&lt; 2;
      b = (byte)(a&lt;&lt;2);
      "Binary Equivalent of b : "+Integer.toBinaryString(b); // gives 0 
  
      byte i1 = -5,i2;
      int s;
      s = i1&lt;&lt;2;
      i2 = (byte)(i1&lt;&lt;2);
  
      Integer.toBinaryString(i2); //gives 11111111111111111111111111101100   WHY?
  </code></pre>
  
  <p>I have declared <code>i2</code> to be of <code>byte</code>. Hence it should contain <code>8 bits</code>(a byte). Why <code>32</code> <code>bits</code>. Does top <code>3 bytes</code> of the result needs to be discarded. This happens to be only in case of negative numbers(here <code>-5</code>). Doesn't happens with <code>64</code>. Please suggest.</p>