Java operators perform calculations, compare values, combine conditions and assign results. Operator precedence decides how an expression groups when you do not supply parentheses. For example, multiplication groups before addition, so 2 + 3 * 4 evaluates to 14. Parentheses can change that grouping or make an intended grouping easier to see.
Precedence is not the same as the order in which operands are evaluated. Java evaluates operands from left to right, while precedence determines the structure of the operation. Keep expressions simple enough that readers do not need to memorize a table to understand them.
Arithmetic, remainder and numeric types
The arithmetic operators +, -, *, / and % add, subtract, multiply, divide and compute a remainder. Integer division discards the fractional part toward zero. The remainder operator is useful for questions such as whether a number is even: value % 2 == 0. For negative operands, Java’s remainder can be negative, so it is not always a mathematical nonnegative modulo result.
Unary + and - apply to one operand. Increment and decrement change a variable by one. Prefix ++count yields the updated value, while postfix count++ yields the previous value as part of an expression. For beginners, write increments as separate statements unless the returned value is essential. Combining several changes in one expression makes evaluation harder to explain and offers little readability benefit.
Comparisons and logical operators
The operators <, <=, > and >= compare ordered numeric values. == tests equality and != tests inequality. Their result is boolean, so comparisons fit directly into if conditions. Use String.equals for string content comparisons; == on references asks whether they refer to the same object, not whether their characters match.
The logical operators && and || combine boolean expressions. && requires both to be true; || requires at least one. The ! operator negates one boolean value. An inclusive age range needs two comparisons joined by &&: age >= 18 && age <= 65. Java does not accept mathematical chained comparison notation such as 18 <= age <= 65 because the first comparison already produces a boolean.
Short-circuit evaluation protects a condition
With left && right, Java does not evaluate right if left is false. With left || right, Java does not evaluate right if left is true. This behavior is called short-circuiting and can protect operations that are valid only after another check succeeds.
For example, text != null && text.length() > 0 checks the reference before using it. Reversing the operands can attempt a method call on null before the protective test. Similarly, divisor != 0 && total / divisor > 2 avoids integer division by zero. The & and | operators can also work on booleans but evaluate both operands; do not substitute them casually for && and ||. Their integer forms perform bitwise operations, which serve a different purpose.
Precedence and associativity together
A useful beginner grouping order is parentheses, unary operators, multiplication/division/remainder, addition/subtraction, relational comparisons, equality, &&, || and assignment. This summary omits less common categories rather than claiming to be the entire language table. Conditional ?: expressions and bitwise operators have their own positions, so use parentheses when those categories mix.
Operators at the same precedence often group left to right. Thus 20 / 5 * 2 groups as (20 / 5) * 2 and yields eight. Assignment groups right to left, so a = b = 3 assigns three to both variables. Associativity determines grouping, while operand evaluation remains governed by Java’s evaluation rules. A clear intermediate result often communicates intent better than relying on either rule implicitly.
Assignment, compound assignment and bitwise forms
The = operator stores a value. Compound assignments such as += and *= combine an operation with assignment to the same variable. They include an implicit conversion back to the left-hand type, so short count = 1; count += 2; can compile where count = count + 2; needs an explicit narrowing cast. That convenience can also hide overflow.
Bitwise &, | and ^ operate on integer bit patterns; ~ complements bits, and <<, >> and >>> shift them. The two right-shift operators differ in their treatment of the high bits. These are useful for masks and packed data, not replacements for ordinary arithmetic by habit. Choose conventional arithmetic for ordinary totals and use bitwise operations when the representation itself is part of the problem.
Practice with explained solutions
Task 1. Write a condition accepting a score from 0 through 100, including both boundaries.
Solution. Use score >= 0 && score <= 100. Test -1, 0, 100 and 101 to verify the permitted range.
Task 2. Predict 18 - 6 / 3, then add parentheses so subtraction occurs first.
Solution. The original yields 16. (18 - 6) / 3 yields 4 because the parentheses change the grouping.
Java Summary
- Precedence controls grouping; it does not reverse Java's left-to-right operand evaluation.
- Use parentheses to make mixed operations readable.
- Place safety checks first in short-circuit conditions, and keep increments separate when possible.
- Continue with boolean expressions.
Java Examples
Each example shows the code, the output it produces and what each part does.
Make grouping visible
Save this complete program as PrecedenceTotals.java. Compile with javac --release 17 PrecedenceTotals.java and run with java PrecedenceTotals.
public class PrecedenceTotals {
public static void main(String[] args) {
System.out.println(2 + 3 * 4);
System.out.println((2 + 3) * 4);
System.out.println(20 / 5 * 2);
}
}14
20
8Line-by-line explanation
- Lines 1 to 7Multiplication occurs within the first expression before addition, producing twelve plus two. Parentheses in the second expression force the addition to produce five before multiplication. Division and multiplication have equal precedence and group left to right in the last expression, giving four times two. No variable changes are involved, so you can focus entirely on grouping.
Protect a nullable reference
Save this complete program as SafeCondition.java. Compile with javac --release 17 SafeCondition.java and run with java SafeCondition.
public class SafeCondition {
public static void main(String[] args) {
String text = null;
boolean hasText = text != null && !text.isEmpty();
System.out.println(hasText);
text = "Ready";
System.out.println(text != null && !text.isEmpty());
}
}false
trueLine-by-line explanation
- Lines 1 to 9When text is null, the first comparison is false and && skips the isEmpty call. After assignment to Ready, the reference check succeeds and the nonempty check also succeeds. This ordering is necessary: placing the method call first can throw NullPointerException. The condition therefore demonstrates both a logical rule and a concrete reason to preserve operand order.
Distinguish prefix and postfix
Save this complete program as CounterExpressions.java. Compile with javac --release 17 CounterExpressions.java and run with java CounterExpressions.
public class CounterExpressions {
public static void main(String[] args) {
int count = 4;
int previous = count++;
int updated = ++count;
System.out.println(previous);
System.out.println(updated);
System.out.println(count);
}
}4
6
6Line-by-line explanation
- Lines 1 to 10The postfix operation contributes four to previous and then leaves count at five. The prefix operation first increases count to six and contributes six to updated. The last output confirms the current stored value. In normal application code, separate increments from larger expressions unless you need this distinction; the example isolates it so the effect is measurable.
Common Java Mistakes
Using = where == was meant
Avoid confusing = with ==. Assignment changes a variable; equality compares values. With booleans, an accidental assignment in a condition can compile and change state, making it especially misleading. Use descriptive boolean expressions directly where possible. Also avoid a correct but dense mixture of arithmetic, increments and method calls; intermediate variables reduce the opportunity for evaluation-order mistakes.
Java FAQ
Must I memorize every precedence level?
Learn common arithmetic and logical relationships, then use parentheses for unfamiliar mixtures. Readability matters more than demonstrating memorization.
Does && always evaluate both conditions?
No. It evaluates the second only when the first is true. Keep side effects out of conditions unless that behavior is deliberate and clearly explained.
What is operator associativity?
Associativity decides how operators of the same precedence group. Most binary operators group left to right, so 10 - 4 - 3 is (10 - 4) - 3, which is 3. Assignment groups right to left, so a = b = 5 first sets b to 5 and then copies that value into a.
Why does x += 1.5 compile when x = x + 1.5 doesn't?
A compound assignment includes a hidden cast back to the variable's type. For an int x, x += 1.5 means x = (int) (x + 1.5), so the fraction is silently dropped. The plain form x = x + 1.5 is rejected with "possible lossy conversion from double to int", which is the more honest warning.
Why does a ternary inside string concatenation need parentheses?
The + operator has higher precedence than ?:, so "Total: " + isMember ? 5 : 10 is read as ("Total: " + isMember) ? 5 : 10, which doesn't compile because a String isn't a boolean. Write "Total: " + (isMember ? 5 : 10) instead.
Java Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
What is the result of (2 + 3) * 4?
Why check text != null before text.isEmpty()?
Java Quiz
2 questions to check what you learned.
Which operation groups first in 2 + 3 * 4?
- Multiplication
- Addition
- Assignment
When does false && right skip right?
- Always
- Only for numeric right operands
- Never