Search code examples
javaif-statementinitialization

Can you store a variable inside a if-clause?


I'm kinda waiting for a 'no' answer on this question.

I was interested if you can save a variable at the same time when you checking it in an if-clause.

Let's say I have this 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.");
}

I handling now to "failure" -states independently, even if the outcome is the same. I could get them together like this:

if(foo!=null && foo.getBar()!=null){
  Bar bar = foo.getBar();
  System.out.println("Success: " + bar);
} else {
  System.out.println("Failure.");
} 

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:

if(foo!=null && (Bar bar = foo.getBar())!=null){
  Bar bar = foo.getBar();
  System.out.println("Success: " + bar);
} else {
  System.out.println("Failure.");
}

I would have to break it up to two different if's again if I would like to do

Bar bar = foo.getBar();
if (bar!=null) ...

Solution

  • This is the closest you can get:

    Bar bar;
    if(foo!=null && (bar = foo.getBar())!=null){
      System.out.println("Success: " + bar);
    } else {
      System.out.println("Failiure.");
    }