简体   繁体   中英

Priority of equality and conditional operators in java

I run the following code snippet

System.out.println(T1() ? F1() : T2() == T3() ? F2() : T4());
public static boolean T1() { System.out.println("true1"); return true; }
public static boolean T2() { System.out.println("true2"); return true; }
public static boolean T3() { System.out.println("true3"); return true; }
public static boolean T4() { System.out.println("true4"); return true; }
public static boolean F1() { System.out.println("false1"); return false; }
public static boolean F2() { System.out.println("false2"); return false; }

I get the output

true1
false1
false

The first ternary operator been evaluated before evaluating the equality operator, but according to oracle documentation , equality operator has greater priority than the ternary one, therefore the equality operator must be evaluated before the ternary one.

Whats the reason of such code behavior?

JLS 15.25

The conditional operator is syntactically right-associative (it groups right-to-left). Thus, a?b:c?d:e?f:g means the same as a?b:(c?d:(e?f:g)).

And in your case :

T1() ? F1() : (T2() == T3() ? F2() : T4())
  a     b            c         d       e

T1() is evaluated true, returning true, so only F1() is evaluated next.

You seem to misunderstand what priority means. The fact that == has higher priority than the ternary operator does not mean that in an expression all == subexpressions are evaluated first. Priority is solely a means to omit parentheses in certain cases.

For example, the expression

a == b ? c : d

could be equivalent to either (a==b) ? c : d (a==b) ? c : d or a == (b ? c : d) . The fact that == has higher priority means that it is actually equivalent to the first.

In the expression

a ? b : c == d

there is no ambiguity, it is always equivalent to a ? b : (c == d) a ? b : (c == d) . Since the ternary operator is lazily evaluated, if a holds, c == d is never evaluated.

The T2() == T3() is never evaluated. Your code is equal to:

if(T1()) {
  System.out.println(F1());
}
else {
  if(T2() == T3()) {
    System.out.println(F2());
  }
  else {
    System.out.println(T4());
  }
}

Here you clearly see why it is never evaluated - because T1() is true and the else block is never entered.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM