Java Operators: Types, Precedence and Unary Operators (OCP 21)
The OCP Java 21 rules for operators: unary, binary and ternary operators, the full precedence ladder with associativity, left-to-right operand evaluation, logical and bitwise complement, negation, and the prefix and postfix increment and decrement operators.
kvi5hnuCode Sprout team member8 min readOn this page
Operators combine values into new values. Many questions on the exam come down to computing exactly what an expression produces, or noticing that it doesn't compile. This article explains how Java decides what to evaluate first and covers the operators with a single operand, including ++ and --, which turn up in a large number of exam questions. The next two articles cover arithmetic and assignment, and then comparisons and logic.
Operators and operands
An operator is a symbol applied to one or more operands (variables, literals or other expressions) to produce a result:
int c = a + b; // + has operands a and b; = stores the result in c
Java operators come in three sizes:
| Kind | Operands | Examples |
|---|---|---|
| Unary | one | -x, !done, count++ |
| Binary | two | a + b, x < y, p && q, n = 5 |
| Ternary | three | ok ? "yes" : "no" (Java has only this one) |
Assignment is an operator too. n = 5 is an expression whose value is 5, which is why a = b = 0 works. Article 9 covers this.
Precedence and associativity
Precedence decides how an expression without parentheses is grouped. * has higher precedence than +, so 2 * h + 2 * w means (2 * h) + (2 * w). Assignment has the lowest precedence, so it happens last.

| # | Operators | Grouping |
|---|---|---|
| 1 | Postfix: x++ x-- | left to right |
| 2 | Prefix and unary: ++x --x +x -x ~x !x (type) x | right to left |
| 3 | Multiplicative: * / % | left to right |
| 4 | Additive: + - | left to right |
| 5 | Shift: << >> >>> | left to right |
| 6 | Relational: < > <= >= instanceof | 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: ? : | right to left |
| 14 | Assignment: = += -= *= /= %= &= ^= |= <<= >>= >>>=, and the lambda arrow -> | right to left |
Memorize this order. The exam doesn't test shift operators, but you should recognize them. A good memory aid: unary, then arithmetic, then comparison, then logic, then ternary, then assignment.
Associativity (the grouping column) settles ties between operators at the same level. 10 - 4 - 3 groups left to right as (10 - 4) - 3, which is 3. a = b = c groups right to left as a = (b = c). - - x and !!flag apply the inner operator first.
int price = 2 * 5 + 3 * 4 - 8; // 10 + 12 - 8 = 14
int price2 = 2 * ((5 + 3) * 4 - 8); // 2 * (32 - 8) = 48
Parentheses override precedence. They must be balanced and properly nested, and only round parentheses are allowed: 3 + [(4 * 2) + 4] doesn't compile, because square brackets are for arrays. Extra parentheses are always legal and often make real code clearer.
Precedence is not evaluation order
This point is subtle, and it explains many exam answers. Precedence only decides grouping. Java separately guarantees that the operands of a binary operator are evaluated left to right: the left operand completely, then the right one, then the operator itself.
static int show(String label, int v) { System.out.print(label + " "); return v; }
int r = show("A", 2) + show("B", 3) * show("C", 4); // prints A B C; r = 14
The multiplication happens before the addition, but A is still evaluated first. This matters whenever an operand has a side effect, such as a method that prints or a ++ that changes a variable.
Unary operators
| Operator | Example | Meaning |
|---|---|---|
| Logical complement | !done | Flips a boolean |
| Bitwise complement | ~bits | Flips every bit of an integer |
| Unary plus | +x | The value itself (it does promote byte, short and char to int) |
| Negation | -x | Reverses the sign |
| Increment | ++x, x++ | Adds 1 to a variable |
| Decrement | --x, x-- | Subtracts 1 from a variable |
| Cast | (int) d | Converts to another type (article 9) |
!, ~, - and +
boolean asleep = false;
asleep = !asleep; // true
int bits = 70;
int flipped = ~bits; // -71: for integers, ~n equals -n - 1
int back = ~flipped; // 70
double t = 1.5;
t = -t; // -1.5
t = -(-t); // -1.5 again: two negations cancel
Each operator works only on its own kind of operand, and Java never converts between numbers and boolean:
int a = !5; // DOES NOT COMPILE: ! needs a boolean
boolean b = -true; // DOES NOT COMPILE: - needs a number
boolean c = ~true; // DOES NOT COMPILE: ~ needs an integer type
boolean d = !0; // DOES NOT COMPILE: 0 is not false in Java
In Java, 1 is not true and 0 is not false. Questions that mix them up never compile.
Spaces matter with minus signs. -(-t) and - -t are two negations, but --t is the decrement operator. --5 doesn't compile at all, because only a variable can be decremented.
Increment and decrement
++ and -- add or subtract 1 and store the result back in the variable. Where you put them decides which value the expression produces:
| Form | Changes the variable | Value of the expression |
|---|---|---|
++x (pre-increment) | x becomes x + 1 | the new value |
--x (pre-decrement) | x becomes x - 1 | the new value |
x++ (post-increment) | x becomes x + 1 | the old value |
x-- (post-decrement) | x becomes x - 1 | the old value |
int visitors = 5;
System.out.println(visitors++); // 5 (then visitors is 6)
System.out.println(visitors); // 6
System.out.println(++visitors); // 7
System.out.println(visitors--); // 7 (then visitors is 6)
The operand must be a variable of a numeric type (or a numeric wrapper, through unboxing). 5++, ++x++ and flag++ for a boolean don't compile, and neither does incrementing a final variable. Unlike binary arithmetic, ++ and -- keep the variable's type: short s = 10; s++; compiles without a cast, and so does char c = 'a'; c++;, which makes c equal to 'b'.
Tracing a tricky expression
For exam questions that mix several increments, work left to right, writing the value each operand produces and the variable's new value after it:
int a = 2;
int b = a++ + a++ * --a;
| Operand | Value used | a afterwards |
|---|---|---|
a++ | 2 | 3 |
a++ | 3 | 4 |
--a | 3 | 3 |
Then apply precedence to the values: 2 + 3 * 3 = 11. So b is 11 and a is 3.
Two patterns appear often:
x = x++;leavesxunchanged. The old value is saved,xis incremented, and then the assignment stores the saved old value back.x+++yis read as(x++) + y. The compiler takes the longest operator it can at each point, so it reads++before+.
What's current
- Nothing in this article changed in Java 22 through 25, so the rules apply to both the Java 21 exam (1Z0-830) and the Java 25 exam (1Z0-831).
- The operator set and the precedence table have been stable since Java 1.0. The
instanceofoperator gained patterns in Java 16 (article 11), and primitive types ininstanceofare a preview from Java 23 on, not part of either exam.
Exam traps from this article
A complete example
public class Solution {
// Prints a label and returns the value, so we can watch evaluation order.
static int show(String label, int value) {
System.out.print(label + " ");
return value;
}
public static void main(String[] args) {
// 1. Precedence groups the expression; operands are still evaluated left to right.
int result = show("A", 2) + show("B", 3) * show("C", 4);
System.out.println("=> " + result);
// 2. Parentheses change the grouping, not the left-to-right evaluation.
result = (show("A", 2) + show("B", 3)) * show("C", 4);
System.out.println("=> " + result);
// 3. Prefix vs postfix.
int visitors = 5;
System.out.println("visitors++ gives " + visitors++ + ", now " + visitors);
System.out.println("++visitors gives " + ++visitors + ", now " + visitors);
// 4. A classic exam expression: track the variable after every step.
int a = 2;
int b = a++ + a++ * --a; // 2 + (3 * 3); a goes 3, 4, 3
System.out.println("b=" + b + ", a=" + a);
// 5. x = x++ leaves x unchanged: the old value is saved, x is bumped, then the old value is stored.
int count = 7;
count = count++;
System.out.println("count=" + count);
// 6. The other unary operators.
boolean asleep = false;
int bits = 70;
double temp = 1.5;
System.out.println(!asleep + " " + ~bits + " " + -temp + " " + -(-temp) + " " + +bits);
// 7. ++ and -- keep the variable's type, so no cast is needed on a short or char.
short s = 32_767;
s++; // wraps around silently
char grade = 'B';
grade--;
System.out.println(s + " " + grade);
}
}
Output:
A B C => 14
A B C => 20
visitors++ gives 5, now 6
++visitors gives 7, now 7
b=11, a=3
count=7
true -71 -1.5 1.5 70
-32768 A
Points to notice:
- Both expressions print
A B C: parentheses change the result (14 versus 20) but not the order in which the operands run. - In the
visitors++line, the string is built left to right, so thevisitorsat the end of that line already sees the incremented value. - Incrementing the largest
shortwraps around to the smallest one. Integer overflow never throws an exception (article 9).
Common questions
Is i = i++ + ++i; legal, and what does it do?
It's legal, and Java fully defines the result. With i = 1, the left operand produces 1 (and i becomes 2), the right operand makes i 3 and produces 3, so i ends up as 4. Unlike in C, there's no undefined behavior, but avoid writing this in real code.
Is the cast operator really a unary operator?
Yes. (int) x takes one operand and has the same high precedence as the other prefix operators. So (int) 3.7 + 0.5 casts first, giving 3 + 0.5, which is 3.5.
Do I need to know the shift operators?
Not for 1Z0-830, beyond recognizing them and knowing they sit between additive and relational operators. << shifts left, >> shifts right keeping the sign, and >>> shifts right filling with zeros.
Why does "total: " + 1 << 3 fail to compile?
+ binds tighter than <<, so the expression means ("total: " + 1) << 3, which shifts a String. Write "total: " + (1 << 3) instead.
Can I apply ++ to an Integer?
Yes. The value is unboxed, incremented and boxed into a new Integer object. Wrapper objects never change.
Summary
- Operators take one, two or three operands. Java's only ternary operator is
? :. - Precedence, from highest: postfix, prefix and unary, multiplicative, additive, shift, relational, equality,
&,^,|,&&,||, ternary, assignment. Parentheses override it. - Most binary operators group left to right. Unary, ternary and assignment operators group right to left.
- Operands are always evaluated left to right, whatever the precedence.
!works only onboolean,~only on integer types and-only on numbers. Java never treats numbers as booleans.- Prefix
++/--produce the new value and postfix forms produce the old value. Both change the variable and keep its type.
Practice quiz
Test yourself with the operators, precedence and unary operators quiz: 10 exam-style questions with explanations.
Previous: Java Variable Scope and Garbage Collection (OCP 21)
Next: Java Arithmetic, Numeric Promotion, Casting and Assignment Operators (OCP 21)
Related reading
- Java Variable Scope and Garbage Collection (OCP 21)
- Declaring and Initializing Java Variables: Identifiers, Defaults and var (OCP 21)
- Java Primitive Types, Literals, Wrapper Classes and Text Blocks (OCP 21)
- Creating Objects in Java: Constructors, Instance Initializers and Order of Initialization (OCP 21)
- Java Packages and Imports: Wildcards, Conflicts, Compiling and the Class Path (OCP 21)

More in OCP Java 21
OCP Java 21 Mock Exam 3 (1Z0-830)
The third full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), weighted toward the hardest areas: streams, concurrency, generics, modules and I/O. 120 minutes, 68% to pass, with explanations.
OCP Java 21 Mock Exam 2 (1Z0-830)
The second full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830): new questions on every objective, with more multi-select. 120 minutes, 68% to pass, with an explanation for every answer.
OCP Java 21 Mock Exam 1 (1Z0-830)
A full 50-question mock exam for the OCP Java SE 21 Developer exam (1Z0-830), covering every objective at exam difficulty. 120 minutes, 68% to pass, with an explanation for every answer.
Quiz: Final Review (OCP 21)
Ten exam-style questions mixing the most-tested OCP Java 21 rules from the final checklist: promotion, String immutability, overloading, initialization order, collections, streams, exceptions and switch patterns, with explanations.
Discussion
Sign in to ask a question or share what you learned.