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

if(true || false){

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)?

  • 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. – user40980 Nov 12 '15 at 2:45
  • @MichaelT But this is for C, my question was for Java? – user2924127 Nov 12 '15 at 3:06
  • 1
    The JLS link explains the "this is how it works." The C link explains what it is. – user40980 Nov 12 '15 at 3: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. – user40980 Nov 12 '15 at 15:48

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

  • @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. – user40980 Nov 12 '15 at 15:11

Not the answer you're looking for? Browse other questions tagged or ask your own question.