2

Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?

I use Optional and I have something like that :

if (!opt.isPresent() || opt.get() == currentPlayer.getSelectedRegion())

and there will be a problem if the first test is true and java compute the second test.

Spooky
  • 315
  • 1
  • 3
  • 12
  • 1
    And additionally to the answers, the reference in the [java-8-specification](https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.24). – MalaKa Sep 23 '15 at 14:06

4 Answers4

3

If first condition is true second condition is not evaluated.

If first condition is false also second condition is evaluated.

That's why you can write a code like the following without a NullPointerException

if (str == null || str.length() == 0) {
     // do something
}

The operator | (instead of || ) will evaluated both conditions

So the code

if (str == null | str.length() == 0) {
     // do something
}

can generate a NullPointerException if str is null

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
2

Does java calculate the second condition in ( test1 || test2 ) if the first one is true ?

No. Boolean or will short-circuit, the first true is sufficient to make the expression true. No further conditions will be evaluated after that.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

No, java short-cut operators, the second argument is not evaluated if the first is. Ore more formal:

  • for x || y, y is only evaluated if x is false; and
  • for x && y, x is only evaluated if y is true.

This will increase performance and can be both useful and tricky:

  • usefull: to prevent you from doing things such that an error is thrown. The most typical example is the null check:

    if(x != null && x.someTest())
    

    this will prevent .someTest being called if x is null.

  • tricky: the problematic aspect can be if you call a method that does not only return something, but changes state as well. For instance:

    public class Foo {
        private int checked = 0;
    
        bool someCondition () {
            return (checked % 2) == 0;
        }
    
        bool neverChecked () {
            checked++;
            return checked == 1;
        }
    }
    

    if you now call:

    if(foo.someCondition() || foo.neverChecked());
    

    this is one of the main reasons it is adviseable to keep "getters" (thinks that calculate things of an object), and "setters" (things that modify the state of an object), clearly separated. From the moment you start mixing, one can get complicated behavior in some circumstances.

it can be the intention that you always increment checked, but it will only if .someCondition happens to be false.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
1

If you use the || and &&, rather than the | and &, Java will not bother to evaluate the right-hand operand.

thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23