Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 201 ยท Operators

Operator Precedence and the Ternary Operator

See Java's full operator precedence table, how associativity and left-to-right evaluation work, and how to use the ?: ternary operator and instanceof safely.

What does 2 + 3 * 4 equal? You probably answered 14, not 20, because you learned in school that multiplication comes before addition. Java follows the same idea, but it has far more operators than a math class: comparisons, logical operators, bit shifts, casts, instanceof, assignment and the conditional ?:. Operator precedence decides which operator grabs its operands first, and associativity breaks ties between operators of the same level.

This lesson gives you the complete precedence table, explains the difference between precedence and evaluation order (they are not the same thing), and covers the two operators that haven't had their own lesson yet: the ternary operator ?: and instanceof. Along the way you'll see the mistakes that come from guessing, and the simple habit that avoids them.

Precedence and associativity

Precedence works like invisible parentheses. In 2 + 3 * 4, * has higher precedence than +, so Java reads it as 2 + (3 * 4). When two operators have the same precedence, associativity decides. Most binary operators are left-associative: 20 - 5 - 3 means (20 - 5) - 3, which is 12, not 20 - (5 - 3), which would be 18.

A few operators are right-associative: assignment, the ternary operator and the unary operators. a = b = 0 means a = (b = 0), as you saw in Assignment and Increment Operators.

Java Precedence in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The string lines are worth a second look. + is left-associative, so "Sum: " + 1 + 2 first builds "Sum: 1" and then appends 2. In 1 + 2 + " items", the first + sees two numbers and adds them before the string ever appears. And 'a' + 'b' is 195, because two char values are promoted to int (97 + 98), as explained in Arithmetic Operators.

The precedence table

Here is every Java operator, from highest precedence (applied first) to lowest. Operators in the same row share a level.

Level Operators Description Associativity
1 x++ x-- postfix increment and decrement left to right
2 ++x --x +x -x ~ ! (type) unary operators and casts right to left
3 * / % multiplicative left to right
4 + - additive and string concatenation left to right
5 << >> >>> shifts left to right
6 < > <= >= instanceof relational and type test left to right
7 == != equality left to right
8 & bitwise or logical AND left to right
9 ^ bitwise or logical XOR left to right
10 | bitwise or logical OR left to right
11 && conditional AND left to right
12 || conditional OR left to right
13 ? : ternary conditional right to left
14 = += -= *= /= %= &= ^= |= <<= >>= >>>= -> assignment and lambda arrow right to left

Member access (obj.field, obj.method()), array indexing (arr[i]) and method calls bind even tighter than level 1, so -list.size() negates the size, and arr[i]++ increments the element.

Three groupings are worth memorizing because they match how you think: arithmetic > comparison > logical, so a + b > c && d < e means ((a + b) > c) && (d < e) with no parentheses needed. Everything else, look up or parenthesize.

The bitwise trap

The one place where the table really surprises people is levels 7 to 10. The bitwise operators &, ^ and | sit below == and !=. That was a historical decision inherited from C, and it means this doesn't do what it looks like:

Java
if (flags & MASK != 0) { ... }   // parsed as flags & (MASK != 0): compile error
if ((flags & MASK) != 0) { ... } // correct

In C the first line silently compiles and gives the wrong answer; in Java it's a compile error because you can't & an int with a boolean. Either way, always put parentheses around a bitwise expression before comparing it. Bitwise and Shift Operators uses this pattern throughout.

Precedence is not evaluation order

Precedence decides how an expression is grouped. It does not decide which operand is computed first. Java has a separate, simple rule for that: operands are always evaluated left to right, and both operands of a binary operator are evaluated before the operator itself is applied (except for the short-circuit operators &&, || and ?:).

Java Grouping vs evaluation order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Even though b() * c() is grouped first, a() is called first, because it's the leftmost operand. The second example shows why this matters: the array index is evaluated before the right side, so the value 2 goes into arr[1].

This guarantee is one of Java's strengths: unlike C and C++, the same expression gives the same result on every compiler and JVM. But code that depends on it is hard to read. If evaluation order matters for correctness, split the expression into separate statements.

The ternary operator ?:

The conditional operator, usually called the ternary operator because it takes three operands, is a compact if-else that produces a value:

Java
condition ? valueIfTrue : valueIfFalse

The condition must be a boolean. If it's true, the whole expression evaluates to the second operand; otherwise to the third. Only the chosen branch is evaluated, so the ternary short-circuits like && and ||.

Java Choosing a value with ?:

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The ternary sits near the bottom of the precedence table, just above assignment. That's why larger = a > b ? a : b needs no parentheses: the comparison happens first, then the ternary, then the assignment. But inside string concatenation you do need them. Without the parentheses, "item" + items == 1 ? "" : "s" would be parsed as ("item" + items) == 1 ? ..., which compares a String with an int and fails to compile.

The type of a ternary expression

Both branches must produce compatible types, and the result has a single type worked out from both. For numbers, that means numeric promotion, which can surprise you:

Java Ternary type surprises

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The first two lines print 1.0, not 1: when one branch is an int and the other a double, both become double. That rule applies even to Integer and Double objects, which are unboxed and promoted. The last example is a real production bug: because the other branch is a primitive int, Java unboxes cached, and unboxing null throws. Making both branches the same type (flag ? cached : Integer.valueOf(0)) avoids it. You'll learn more about boxing in Wrapper Classes and Autoboxing.

Nested ternaries

Because ?: is right-associative, you can chain it:

Java
String size = n < 10 ? "small"
            : n < 100 ? "medium"
            : "large";

Formatted like this, one condition per line, a short chain is readable. Nesting a ternary inside the middle operand, or chaining more than three or four cases, is not. For anything bigger, use if/else if (see if, else if and else) or a switch expression (see switch Statements and Expressions).

Use the ternary operator to choose between two values. Don't use it to choose between two actions: ready ? start() : wait(); doesn't even compile as a statement, and an if is clearer anyway.

The instanceof operator

instanceof tests whether an object is an instance of a class or interface, and produces a boolean. It sits at the same level as < and >, so it binds tighter than ==, && and ||. Since Java 16 it can also declare a pattern variable that is already cast to the tested type:

Java instanceof and pattern variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

A few precedence details make this work:

  • In thing instanceof String s && s.length() > 3, the instanceof test is applied first, and && only evaluates the right side when it's true, so s is guaranteed to exist there.
  • To negate the test you need parentheses: !(thing instanceof String). Writing !thing instanceof String applies ! to thing first, which doesn't compile.
  • null instanceof AnyType is always false, so instanceof doubles as a null check.

Pattern matching goes much further, with switch patterns and record patterns, in Pattern Matching.

Writing readable expressions

The precedence table is a tool for reading code, not a challenge for writing it. A few habits keep expressions clear:

  • Add parentheses when mixing operator families, especially && with ||, bitwise operators with comparisons, and ternaries inside concatenation. Redundant parentheses cost nothing.
  • Name intermediate results. boolean isWeekend = ...; followed by if (isWeekend && !isHoliday) beats one long line.
  • Keep side effects out of complex expressions. ++, assignments and method calls with side effects belong in their own statements.
  • Break long expressions across lines at an operator, with the operator at the start of the new line so it's easy to see.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does IO.println(10 + 2 * 3 - 4 / 2); print?

    • and / come first: 2 * 3 = 6 and 4 / 2 = 2. Then left to right: 10 + 6 - 2 = 14.
  2. 2. What does IO.println("Total: " + 2 + 3); print?

    + is left-associative. "Total: " + 2 gives "Total: 2", and then 3 is appended as text.
  3. 3. What does IO.println(true ? 7 : 7.5); print?

    When one branch is an int and the other a double, the result type is double, so the chosen value 7 is printed as 7.0.
  4. 4. How does Java group a || b && c?

    && has higher precedence than ||, just as * binds tighter than +. Parentheses make the intent obvious to readers.
  5. 5. In int r = f() + g() * h();, which method is called first?

    Precedence controls grouping, not the order of evaluation. Java always evaluates operands left to right, so f() runs first, then g(), then h().

Summary

  • Precedence decides how operators group; associativity breaks ties at the same level. Most operators are left-associative; unary, ternary and assignment operators are right-associative.
  • Arithmetic binds tighter than comparison, which binds tighter than &&, which binds tighter than ||. Casts bind tighter than arithmetic.
  • Bitwise &, ^ and | rank below ==, so always write (flags & MASK) != 0.
  • Operands are evaluated left to right, whatever the precedence.
  • condition ? a : b picks a value; only the chosen branch runs. Mixed numeric branches are promoted, and a null wrapper paired with a primitive throws.
  • instanceof tests an object's type, can bind a pattern variable, is false for null, and needs parentheses to be negated.
  • When in doubt, add parentheses or split the expression.

Next: Strings, where you'll start working with text: string literals, immutability, comparing strings and the string pool.