5.1 Java Operators, Precedence & String Concatenation

Key Takeaways

  • Precedence and parentheses determine how operators group. Java evaluates the left operand before the right when it evaluates both.

  • Post-increment (x++) returns the original value before incrementing, whereas pre-increment (++x) increments first and returns the new value

  • A nonzero integer remainder has the sign of the dividend. For example, -17 % 5 is -2, while 17 % -5 is 2.

  • && and || can skip the right operand even when the left completes normally. Boolean & and | evaluate the right operand whenever the left completes normally.

  • The + operator is left-associative and switches from numeric addition to String concatenation as soon as either operand is a String: 2 + 3 + "X" + 2 + 3 evaluates to "5X23"

Last updated: November 2026

Use two passes when reading a compound expression. First group operations by precedence and parentheses. Then evaluate the operands in order, recording any changes from increment, assignment, or other side effects.

The Three Evaluation Rules

When Java evaluates an expression, three separate rules work together:

  1. Operator Precedence determines which operator groups first when two operators sit next to each other (for example, * binds tighter than +).
  2. Associativity breaks ties between operators at the same precedence level (left-to-right for + and *; right-to-left for unary prefix, ternary ?:, and assignment =).
  3. Operand Evaluation Order is left to right for the operands that Java evaluates. When the left operand completes abruptly, evaluation stops. Short-circuit and conditional operators can skip operands even after normal completion.

Java SE 8 Operator Precedence Ladder

Study the relative ordering from highest (tightest binding) to lowest (loosest binding):

Precedence  Category                  Operators                       Associativity
----------  ------------------------  ------------------------------  -------------
1 (Highest) Postfix unary             expr++, expr--                  Left-to-right
2           Prefix unary & cast       ++expr, --expr, +expr, -expr,   Right-to-left
                                      ~, !, (type) expr
3           Multiplicative            *, /, %                         Left-to-right
4           Additive / Concatenation  +, -                            Left-to-right
5           Shift                     <<, >>, >>>                     Left-to-right
6           Relational & type test    <, <=, >, >=, instanceof        Left-to-right
7           Equality                  ==, !=                          Left-to-right
8           Logical / bitwise AND     &                               Left-to-right
9           Logical / bitwise XOR     ^                               Left-to-right
10          Logical / bitwise OR      |                               Left-to-right
11          Short-circuit AND         &&                              Left-to-right
12          Short-circuit OR          ||                              Left-to-right
13          Ternary conditional       ? :                             Right-to-left
14 (Lowest) Assignment & compound     =, +=, -=, *=, /=, %=           Right-to-left

Tip

Remember the core exam shortcuts: unary beats multiplicative, multiplicative beats additive, relational beats equality, & beats ^ beats |, && beats ||, and assignment is always last.

Unary Operator Type Traps

Unary operators are picky about operand types. Applying the wrong unary operator triggers a compile-time error:

OperatorValid Operand TypesExam Trap (Does Not Compile)
++, --Assignable variables with a numeric primitive or numeric wrapper type++5 (literal), ++MAX (final var), ++x++ (not a variable)
+, - (unary)Numeric expressions, including wrappers that unbox to numeric types-true or +false (cannot negate a boolean)
! (complement)boolean / Boolean expressions!0 or !5 (Java does not treat int as boolean)
~ (bitwise NOT)Integral values, including wrappers that unbox to integral types~true or ~3.14

Pre-Increment vs. Post-Increment in Expressions

Both ++x and x++ add 1 to x, but they return different values to the surrounding expression:

  • Post-increment (x++) / Post-decrement (x--): Stores the updated value in x and yields the previous value to the surrounding expression.
  • Pre-increment (++x) / Pre-decrement (--x): Updates x by 1 first, then returns the new value.

Trace the classic exam expression carefully from left to right:

int x = 5;
int result = x++ + ++x;
System.out.println("result = " + result + ", x = " + x);

Step-by-step evaluation:

  1. Left operand x++ reads x (5), returns 5, and increments x to 6.
  2. Right operand ++x increments x from 6 to 7, and returns 7.
  3. Addition computes 5 + 7, assigning 12 to result.
  4. Output: result = 12, x = 7.

Now trace a multi-operator expression mixing precedence and unary updates:

int a = 3;
int b = ++a * 5 / a-- + --a;
System.out.println("b = " + b + ", a = " + a);
  1. Left to right across the operands: ++a updates a to 4 and yields 4.
  2. 4 * 5 yields 20.
  3. a-- yields 4, then updates a to 3.
  4. 20 / 4 yields 5 (multiplicative operators * and / share level 3 and associate left-to-right).
  5. --a updates a from 3 to 2 and yields 2.
  6. 5 + 2 yields 7. Output: b = 7, a = 2.

Warning

Standalone increment statements (x++; or ++x;) behave identically on x, and x++ on the right side of an assignment (x = x++;) overwrites the increment with the original value returned by x++, leaving x unchanged!

Integer Division vs. Remainder (%)

When both operands of / are integer types (byte, short, char, int, long), Java performs truncating integer division toward zero—it discards the fractional part rather than rounding down toward negative infinity. Thus -17 / 5 equals -3 (not -4).

The remainder operator (%) satisfies the identity (a / b) * b + (a % b) == a. Consequently, the sign of a non-zero remainder always matches the sign of the dividend (the left operand a), regardless of the divisor's sign:

System.out.println(17 % 5);    // 2   (3 * 5 + 2 == 17)
System.out.println(-17 % 5);   // -2  (-3 * 5 + (-2) == -17)
System.out.println(17 % -5);   // 2   (-3 * (-5) + 2 == 17)
System.out.println(-17 % -5);  // -2  (3 * (-5) + (-2) == -17)

Watch two additional arithmetic traps:

  • Integer divide by zero: 10 / 0 and 10 % 0 compile cleanly and throw ArithmeticException at runtime.
  • Floating-point divide by zero: 10.0 / 0 evaluates to Infinity, -10.0 / 0 evaluates to -Infinity, and 0.0 / 0.0 or 10.0 % 0.0 evaluates to NaN (no exception is thrown).

Boolean Operators and Short-Circuit Evaluation

These examples apply to boolean values and to Boolean operands after unboxing. For &, |, and ^, the right operand is evaluated if the left completes normally. Even a non-short-circuit operator stops if the left operand throws, including when a null wrapper is unboxed.

  • Logical AND (&): Evaluates both operands; returns true only if both are true.
  • Logical inclusive OR (|): Evaluates both operands; returns true if either is true.
  • Logical exclusive OR (^): Evaluates both operands; returns true if the two operands have different boolean values (true ^ false is true; true ^ true is false). There is no short-circuit XOR because either side can change the result.
  • Short-circuit AND (&&): Evaluates the left operand; if false, skips the right operand and immediately returns false.
  • Short-circuit OR (||): Evaluates the left operand; if true, skips the right operand and immediately returns true.

Exam questions test whether side effects in the right operand actually run:

int count = 5;
boolean r1 = (count > 10) && (++count > 5); // false; right side skipped -> count is 5
boolean r2 = (count > 10) & (++count > 5);  // false; right side runs   -> count is 6
boolean r3 = (count == 6) || (++count > 0); // true;  right side skipped -> count is 6
boolean r4 = (count == 6) | (++count > 0);  // true;  right side runs   -> count is 7
System.out.println(r1 + " " + r2 + " " + r3 + " " + r4 + " " + count);
// Prints: false false true true 7

Short-circuiting is also used as a null guard: if (text != null && text.length() > 0) is safe, whereas replacing && with & throws NullPointerException when text is null.

Left-to-Right + String Concatenation

The + operator is overloaded in Java:

  1. With two numeric operands, + performs addition after unboxing where needed and applying binary numeric promotion.
  2. If either operand is a String, + converts the other operand to a String and performs concatenation.

Because + is left-associative, Java evaluates additions from left to right until it encounters a String, after which each successive + in the same unparenthesized chain is concatenation. Parentheses and higher-precedence operators can still group a separate calculation:

System.out.println(2 + 3 + "X" + 2 + 3);     // "5X23"
System.out.println("X" + 2 + 3);             // "X23"
System.out.println("X" + (2 + 3));           // "X5"
System.out.println("X" + 2 * 3);             // "X6" (* beats +)
System.out.println('a' + 1 + "b");           // "98b" ('a' is 97 + 1 = 98)

Two critical concatenation compiler traps:

  • Mixing + and -: System.out.println("Val: " + 5 - 2); DOES NOT COMPILE. Left-to-right grouping produces ("Val: " + 5) - 2, attempting to subtract an int from a String.
  • Compound assignment (+=): On String, s += 8; concatenates "8" onto s. On narrower primitives like byte b = 10; b += 5;, compound assignment compiles because Java inserts an implicit cast (byte)(b + 5), whereas b = b + 5; fails to compile (possible lossy conversion from int to byte).
Test Your Knowledge

What is the output of the following Java code snippet?

int x = 4;
int y = x++ + ++x * 2 - --x;
System.out.println(y + "," + x);
A

12,5

B

11,5

C

13,4

D

10,4

Test Your Knowledge

What does the following code print?

int n = 10;
boolean a = (n < 5) && (++n > 10);
boolean b = (n >= 10) ^ (n++ == 10);
System.out.println(a + " " + b + " " + n);
A

false true 11

B

false true 12

C

false false 12

D

false false 11

Test Your Knowledge

Which expression evaluates to "7Y25" and compiles without error?

A

3 + 4 + "Y" + 2 + 5

B

"" + 3 + 4 + "Y" + (2 + 5)

C

3 + 4 + "Y" + 7 - 2

D

3 + 4 + 'Y' + 2 + 5

Sections you finish are checked off in the contents.