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) ...
Variable scope. Java allows you to declare variables within the body of a while or if statement, but it's important to remember the following: A variable is available only from its declaration down to the end of the braces in which it is declared.
An if statement checks a boolean value and only executes a block of code if that value is true . To write an if statement, write the keyword if , then inside parentheses () insert a boolean value, and then in curly brackets {} write the code that should only execute when that value is true .
No. That is not allowed in C. According to the ANSI C Grammar, the grammar for the if statement is IF '(' expression ')' statement . expression cannot resolve to declaration , so there is no way to put a declaration in an if statement like in your example.
Using the assignment operator in conditional expressions frequently indicates programmer error and can result in unexpected behavior. The assignment operator should not be used in the following contexts: if (controlling expression)
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.");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With