title: NullPointerException through auto-boxing-behavior of Java ternary operator
body: <p>I tripped across a really strange <code>NullPointerException</code> the other day caused by an unexpected type-cast in the ternary operator. Given this (useless exemplary) function:</p>
  
  <pre><code>Integer getNumber() {
      return null;
  }
  </code></pre>
  
  <p>I was expecting the following two code segments to be exactly identical after compilation:</p>
  
  <pre><code>Integer number;
  if (condition) {
      number = getNumber();
  } else {
      number = 0;
  }
  </code></pre>
  
  <p>vs.</p>
  
  <pre><code>Integer number = (condition) ? getNumber() : 0;
  </code></pre>
  
  <p>.</p>
  
  <p>Turns out, if <code>condition</code> is <code>true</code>, the <code>if</code>-statement works fine, while the ternary opration in the second code segment throws a <code>NullPointerException</code>. It seems as though the ternary operation has decided to type-cast both choices to <code>int</code> before auto-boxing the result back into an <code>Integer</code>!?! In fact, if I explicitly cast the <code>0</code> to <code>Integer</code>, the exception goes away. In other words:</p>
  
  <pre><code>Integer number = (condition) ? getNumber() : 0;
  </code></pre>
  
  <p>is not the same as:</p>
  
  <pre><code>Integer number = (condition) ? getNumber() : (Integer) 0;
  </code></pre>
  
  <p>.</p>
  
  <p>So, it seems that there is a byte-code difference between the ternary operator and an equivalent <code>if-else</code>-statement (something I didn't expect). Which raises three questions: Why is there a difference? Is this a bug in the ternary implementation or is there a reason for the type cast? Given there is a difference, is the ternary operation more or less performant than an equivalent <code>if</code>-statement (I know, the difference can't be huge, but still)?</p>