-1

I am studying operators in Java and I have a problem that I can't solve.

    public static boolean first(){
       System.out.println("first");
       return true;
   }
   public static boolean second(){
       System.out.println("second");
       return true;
   }
   public static boolean third(){
       System.out.println("third");
       return true;
   }
    public static void main(String[] args) {
       if(first() && second() | third()){
           //Do something
       }
    }

The output is "first second third". I think it shoud be "second third first" because | is greater than &&. I don't know where is my mistake but obviously there is one.

2 Answers2

2

Don't confuse operator precedence with evaluation order. Java always evaluates expressions left-to-right:

The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.

So, the output is:

first
second
third

because of the order that the method calls are in the expression:

first() && second() | third()

The actual operators used (&&, | or ||) is irrelevant to the order. A different choice of operators might result in some lines not being printed, but those that are printed will be in this order.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
1

first() && second() | third() is evaluated as first() && (second() | third()) due to operator precedence. And evaluation takes place from left to right, so first() is evaluated first, followed by (second() | third()). In evaluating this latter term, both arguments are evaluated (again starting from the left), since first() is true, and there is no short-circuiting for the | operator.

Did you mean to use a single |?

The less idiosyncratic first() && second() || third() is evaluated as (first() && second()) || third(). first() and second() are both evaluated in this instance (and in that order) since first() returns true. Since second() also returns true, third() would not be evaluated.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • I think that evaluation order is more important than precedence or short-circuiting here. OP expects (and sees) all three expressions evaluated; it seems to be the evaluation order which they are not expecting. – Andy Turner Oct 04 '16 at 08:04