Relational Operator Precedence

Whenever a new operator is introduced you have to ask yourself where it fits in the precedence tree. If you look back at the example in the last section, you'll notice that it was implicitly assumed that the arithmetic was done before the comparison. Otherwise, for instance

boolean test8 = 6*4 < 3*8; // False. 24 is not less than 24

4 < 3 returns false which would then be multiplied by six and eight which would generate a compile time error because you can't multiply booleans. Relational operators are evaluated after arithmetic operators and before the assignment operator. == and != have slightly lower precedences than <, >, <= and >=. Here's the revised order:

  1. *, /, % Do all multiplications, divisions and remainders from left to right.
  2. +, - Next do additions and subtractions from left to right.
  3. <, >, >=, <= Then any comparisons for relative size.
  4. ==, != Then do any comparisons for equality and inequality
  5. = Finally assign the right-hand side to the left-hand side

For example,

boolean b1 = 7 > 3 == true;
boolean b2 = true == 7 > 3;
b = 7 > 3;

Previous | Next | Top | Cafe au Lait

Copyright 1997 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified July 14, 1997