let's say I have a statement
if(stack.pop() == 1 && stack.pop() == 1)
if top of stack is 0, then the second condition won't be implemented, which means it just pops one value at the top. What I want is to pop both, the top and the value after top. Is there any way to do that without using another if-else statement in it?
No, java uses short-circuit evaluation on expressions using || and && . See here for more info. Not all "boolean expressions"; you can use & and | with booleans, and they are not short-circuiting.
The answer is no.
In a complex conditional using a logical and ( && ) the evaluation will short circuit (not execute the second condition) if the first condition is false. In a complex conditional using a logical or ( || ) the evaluation will short circuit if the first condition is true.
Since in a lot of cases, only a single line needs to be executed, you can skip using the curly brackets and a block of code and simply indent the next line, though this only works for a single line: if(true) System. out. println("Inside the if block"); System.
int first = stack.pop();
int second = stack.pop();
if (first == 1 && second == 1)
Use the bitwise AND operator
**:
if( stack.pop() == 1 & stack.pop() == 1 )
This will force the evaluation of both sides.
** I know it by "non-short-circuiting" of logical AND, but it is indeed a bitwise operator that acts on boolean operands (documentation here).
Update: As JBNizet said in his comment below, this code is "fragile", since some developer may "correct" the operator to the short-circuit version. If you choose to use &
instead of storing the values of the method calls (forcing them to run) likewise JBNizet answer, you should write a comment before your if statement.
Yet another one-line and slightly obfuscated way to do this:
if( stack.pop() == 1 ? stack.pop() == 1 : stack.pop() == 1 && false )
Personally I'd go for JB Nizet's way. Makes it as clear as can be exactly what you're trying to do.
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