title: Can you store a variable inside a if-clause?
body: <p>I'm kinda waiting for a 'no' answer on this question.</p>
  
  <p>I was interested if you can save a variable at the same time when you checking it in an if-clause. </p>
  
  <p>Let's say I have this code.</p>
  
  <pre><code>if(foo!=null){
    if(foo.getBar()!=null){
      Bar bar = foo.getBar();
      System.out.println("Success: " + bar);
    } else {
      System.out.println("Failure.");
    }
  } else {
    System.out.println("Failure.");
  }
  </code></pre>
  
  <p>I handling now to "failure" -states independently, even if the outcome is the same. I could get them together like this:</p>
  
  <pre><code>if(foo!=null &amp;&amp; foo.getBar()!=null){
    Bar bar = foo.getBar();
    System.out.println("Success: " + bar);
  } else {
    System.out.println("Failure.");
  } 
  </code></pre>
  
  <p>Much neater code already. if foo is null it will stop there and won't try foo.getBar (in the if) so I won't get a NPE. The last thing i would like to enhance, and the main question: Do I really gave to call on foo.getBar() twice? It would be nice to get away from the second identical call if getBar() would be a very heavy operation. So I am wondering if there is somehow possible to do something similiar to this:</p>
  
  <pre><code>if(foo!=null &amp;&amp; (Bar bar = foo.getBar())!=null){
    Bar bar = foo.getBar();
    System.out.println("Success: " + bar);
  } else {
    System.out.println("Failure.");
  }
  </code></pre>
  
  <p>I would have to break it up to two different if's again if I would like to do </p>
  
  <pre><code>Bar bar = foo.getBar();
  if (bar!=null) ...
  </code></pre>