Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to force java to test two condition regardless the first condition? [duplicate]

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?

like image 963
user2774903 Avatar asked Mar 16 '14 17:03

user2774903


People also ask

Does Java evaluate both conditions?

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.

Does the compiler check all conditions if the first condition is true in case of or operator and false incase of and operator?

The answer is no.

Which operator does not check 2nd condition if 1st condition is false?

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.

How do you skip a condition in Java?

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.


3 Answers

int first = stack.pop();
int second = stack.pop();
if (first == 1 && second == 1)
like image 88
JB Nizet Avatar answered Sep 21 '22 13:09

JB Nizet


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.

like image 21
davidbuzatto Avatar answered Sep 24 '22 13:09

davidbuzatto


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.

like image 4
blgt Avatar answered Sep 23 '22 13:09

blgt