title: Bit shifting in Java
body: <p>Here is a Java program that left shifts the <code>short</code> value of <code>2</code>. I have two questions:</p>
  
  <p>Why does <code>num &lt;&lt; i</code> for values of <code>i</code> between 16 and 29 produce valid results? A <code>short</code> should only hold values from -32,768 to 32,767.</p>
  
  <p>So I thought, maybe <code>System.out.println</code> interprets <code>num &lt;&lt; i</code> as a value larger than a <code>short</code>. But then why does it start producing unexpected values at <code>num &lt;&lt; 30</code>? </p>
  
  <pre><code>public class LeftShift {
  
      public static void main(String[] args)
      {
          short num = 2;
          for (int i = 0; i &lt; 32; i++) {
              System.out.println("Left-shifting 2 by " + i + " places yields: " 
                                  + (num &lt;&lt; i));
          }
      }
  
  }
  </code></pre>
  
  <p>The output:</p>
  
  <pre><code>Left-shifting 2 by 0 places yields: 2
  Left-shifting 2 by 1 places yields: 4
  Left-shifting 2 by 2 places yields: 8
  Left-shifting 2 by 3 places yields: 16
  Left-shifting 2 by 4 places yields: 32
  Left-shifting 2 by 5 places yields: 64
  Left-shifting 2 by 6 places yields: 128
  Left-shifting 2 by 7 places yields: 256
  Left-shifting 2 by 8 places yields: 512
  Left-shifting 2 by 9 places yields: 1024
  Left-shifting 2 by 10 places yields: 2048
  Left-shifting 2 by 11 places yields: 4096
  Left-shifting 2 by 12 places yields: 8192
  Left-shifting 2 by 13 places yields: 16384
  Left-shifting 2 by 14 places yields: 32768
  Left-shifting 2 by 15 places yields: 65536
  Left-shifting 2 by 16 places yields: 131072
  Left-shifting 2 by 17 places yields: 262144
  Left-shifting 2 by 18 places yields: 524288
  Left-shifting 2 by 19 places yields: 1048576
  Left-shifting 2 by 20 places yields: 2097152
  Left-shifting 2 by 21 places yields: 4194304
  Left-shifting 2 by 22 places yields: 8388608
  Left-shifting 2 by 23 places yields: 16777216
  Left-shifting 2 by 24 places yields: 33554432
  Left-shifting 2 by 25 places yields: 67108864
  Left-shifting 2 by 26 places yields: 134217728
  Left-shifting 2 by 27 places yields: 268435456
  Left-shifting 2 by 28 places yields: 536870912
  Left-shifting 2 by 29 places yields: 1073741824
  Left-shifting 2 by 30 places yields: -2147483648
  Left-shifting 2 by 31 places yields: 0
  </code></pre>