0

I have a question in regards to Java conditional if statements. If I have a statement such as this:

if(true || false){
//output
}

Will Java go inside of the the if statement as soon as it sees the true statement or will it still evaluate the false statement? I ask because I will have a condition statement which will have a few conditional tests, each which will require a call to a database:

if(isDatabase1() || isDatabase2() || isDatabase3()){
}

The first test will be a condition which will most likely return true, so I was wondering if it will stop after this and go straight into the if statement, or if it will still test the remaining statements (which then will require useless database calls)?

Robert Harvey
  • 198,589
  • 55
  • 464
  • 673
user2924127
  • 103
  • 4
  • http://stackoverflow.com/a/32415910/471129 – Erik Eidt Nov 12 '15 at 02:08
  • [JLS 15.24](https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.24): Conditional-Or Operator || - If the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. –  Nov 12 '15 at 02:45
  • @MichaelT But this is for C, my question was for Java? – user2924127 Nov 12 '15 at 03:06
  • 1
    The JLS link explains the "this is how it works." The C link explains what it is. –  Nov 12 '15 at 03:07
  • Aside, I've tweaked the title and tags of the duplicate target question as none of the answers were C specific and could be applied to C, C++, C#, Java, JavaScript, Perl, Python and a host of other languages. –  Nov 12 '15 at 15:48

1 Answers1

4

No, they short circuit. More specifically if isDatabase1 returns true then neither isDatabase2 or isDatabase3 will be called. https://en.wikipedia.org/wiki/Short-circuit_evaluation

Sirisian
  • 505
  • 2
  • 8
  • @user2924127 ``||`` and ``&&`` are lazy, whereas ``|`` and ``&`` are not. – Binkan Salaryman Nov 12 '15 at 15:06
  • @BinkanSalaryman `|` and `&` are bitwise operations. They have a ***very*** different use. In languages where the Boolean is its own type (rather than just an int), you cannot have `boolean foo() { ... }` and `boolean bar() { ... }` work with `if(foo() | bar()) { ... }`. It just doesn't work. Trying to use `|` and `&` for logical operators rather than bitwise is most often an error. –  Nov 12 '15 at 15:11