-3

I have two functions: functionA() and functionB(), both have a return type boolean.

I want to continue my execution if either one of them returns true and if functionA returns true I don't want function B to execute.

As && works (if one is false it does not check the other), does || works the same?

if(functionA() || functionB()){
//Do Your Work
}

Will the above code satisfy my requirement?

adarshr
  • 61,315
  • 23
  • 138
  • 167
user2511713
  • 555
  • 3
  • 7
  • 18

7 Answers7

6

As specified by the Java Language Specification, §15.24:

The conditional-or operator || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
3

If your first function returns true then logical OR short circuites your second function.

http://en.wikipedia.org/wiki/Short-circuit_evaluation

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • "By default"? Can you change this behavior in Java?? – Antti Huima Jul 03 '13 at 10:27
  • 1
    @antti.huima Java also has the `&`/`|` _logical_ operators (not bitwise), which will evaluate _all_ conditions even if one is false/true. That is, these two operators do not short circuit. – fge Jul 03 '13 at 10:30
0

Yes this will exactly do what you want. Run functionA() and if that does not return true run functionB()

John Smith
  • 2,282
  • 1
  • 14
  • 22
0

Lazy evaluation in java will avoid your functionB() if functionA() returns true.

if(functionA() | functionB())

Can get you through this mechanism and forces the evaluation of your two functions.

0

Yes it will, if you wanted it to execute both you would have done if(functionA() | functionB()){

note, only one vertical bar

Viktor Mellgren
  • 4,318
  • 3
  • 42
  • 75
0

Yes definitely it will execute function A() and if it will return true then function B() will not run and you other code will be executed as u want.

Manish Doshi
  • 1,205
  • 1
  • 9
  • 17
0
boolean f1 = functionA();
boolean f2 = functionB();

if(f1 || f2){
// if statement
} else {
// else statement
}
Sharma
  • 24
  • 1
  • 1
    this is just sample code, not an answer to the question. Also it is not what the user asked, since it runs both functionA and functionB no matter if the result of functionA is true. – John Smith Jul 22 '13 at 12:24