title: Primitive type 'short' - casting in Java
body: <p>I have a question about the primitive type <code>short</code> in Java. I am using JDK 1.6. </p>
  
  <p>If I have the following: </p>
  
  <pre><code>short a = 2;
  short b = 3;
  short c = a + b;
  </code></pre>
  
  <p>the compiler does not want to compile - it says that it "cannot convert from int to short" and suggests that I make a cast to <code>short</code>, so this:</p>
  
  <pre><code>short c = (short) (a + b);
  </code></pre>
  
  <p>really works. But my question is why do I need to cast? The values of a and b are in the range of <code>short</code> - the range of short values is {-32,768, 32767}.
  I also need to cast when I want to perform the operations -, *, / (I haven't checked for others).</p>
  
  <p>If I do the same for primitive type <code>int</code>, I do not need to cast aa+bb to <code>int</code>. The following works fine:</p>
  
  <pre><code>int aa = 2;
  int bb = 3;
  int cc = aa +bb;
  </code></pre>
  
  <p>I discovered this while designing a class where I needed to add two variables of type short, and the compiler wanted me to make a cast. If I do this with two variables of type <code>int</code>, I don't need to cast. </p>
  
  <p>A small remark: the same thing also happens with the primitive type <code>byte</code>. So, this works:</p>
  
  <pre><code>byte a = 2;
  byte b = 3;
  byte c = (byte) (a + b);
  </code></pre>
  
  <p>but this not:</p>
  
  <pre><code>byte a = 2;
  byte b = 3;
  byte c = a + b;
  </code></pre>
  
  <p>For <code>long</code>, <code>float</code>, <code>double</code>, and <code>int</code>, there is no need to cast. Only for <code>short</code> and <code>byte</code> values. </p>