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 % 5is-2, while17 % -5is2.&&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"
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:
- Operator Precedence determines which operator groups first when two operators sit next to each other (for example,
*binds tighter than+). - Associativity breaks ties between operators at the same precedence level (left-to-right for
+and*; right-to-left for unary prefix, ternary?:, and assignment=). - 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:
| Operator | Valid Operand Types | Exam 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 inxand yields the previous value to the surrounding expression. - Pre-increment (
++x) / Pre-decrement (--x): Updatesxby 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:
- Left operand
x++readsx(5), returns5, and incrementsxto6. - Right operand
++xincrementsxfrom6to7, and returns7. - Addition computes
5 + 7, assigning12toresult. - 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);
- Left to right across the operands:
++aupdatesato4and yields4. 4 * 5yields20.a--yields4, then updatesato3.20 / 4yields5(multiplicative operators*and/share level 3 and associate left-to-right).--aupdatesafrom3to2and yields2.5 + 2yields7. 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 / 0and10 % 0compile cleanly and throwArithmeticExceptionat runtime. - Floating-point divide by zero:
10.0 / 0evaluates toInfinity,-10.0 / 0evaluates to-Infinity, and0.0 / 0.0or10.0 % 0.0evaluates toNaN(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; returnstrueonly if both aretrue. - Logical inclusive OR (
|): Evaluates both operands; returnstrueif either istrue. - Logical exclusive OR (
^): Evaluates both operands; returnstrueif the two operands have different boolean values (true ^ falseistrue;true ^ trueisfalse). There is no short-circuit XOR because either side can change the result. - Short-circuit AND (
&&): Evaluates the left operand; iffalse, skips the right operand and immediately returnsfalse. - Short-circuit OR (
||): Evaluates the left operand; iftrue, skips the right operand and immediately returnstrue.
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:
- With two numeric operands,
+performs addition after unboxing where needed and applying binary numeric promotion. - If either operand is a
String,+converts the other operand to aStringand 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 anintfrom aString. - Compound assignment (
+=): OnString,s += 8;concatenates"8"ontos. On narrower primitives likebyte b = 10; b += 5;, compound assignment compiles because Java inserts an implicit cast(byte)(b + 5), whereasb = b + 5;fails to compile (possible lossy conversion from int to byte).
What is the output of the following Java code snippet?
int x = 4;
int y = x++ + ++x * 2 - --x;
System.out.println(y + "," + x);
12,5
11,5
13,4
10,4
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);
false true 11
false true 12
false false 12
false false 11
Which expression evaluates to "7Y25" and compiles without error?
3 + 4 + "Y" + 2 + 5
"" + 3 + 4 + "Y" + (2 + 5)
3 + 4 + "Y" + 7 - 2
3 + 4 + 'Y' + 2 + 5
Sections you finish are checked off in the contents.