title: Java SE 7 - best way to check nested object for null
body: <p>As far as I know <code>Java SE 8</code> has <code>java.util.Optional&lt;T&gt;</code> class that protects the code against unintended <code>null</code> pointer exceptions. But for some reasons I have to use <code>Java 7</code>.</p>
  
  <p>Take a look at my example:</p>
  
  <pre><code>String version = device.getController().version;
  </code></pre>
  
  <p>What is the best practice to check <code>device</code> and <code>getController()</code> for null?</p>
  
  <p><strong>Option 1:</strong></p>
  
  <pre><code>String version = "unknown";
  if(device!=null){
    if(device.getController()!=null) 
      version = device.getController().version;
  }
  </code></pre>
  
  <p><strong>Option 2:</strong></p>
  
  <pre><code>String version = "unknown";
  if(device!=null &amp;&amp; device.getController()!=null){
    version = device.getController().version;
  }
  </code></pre>
  
  <p>Option 1 is a bit cumbersome, but obviously it will work correctly. The second options is questionable, because the fact that we do not know which part of condition will be checked first and how <code>Java</code> actually do it. There is a point to suggest that <code>Java</code> checks 2 parts of conditions before returning the result. Obviously, the second part will return <code>NullPointerException</code> in case device is null. So, what is the best way to check nested objects in Java 7 and earlier?</p>