Ch 3.1 Operator Basics
Symbols used to process and calculate data in a program are called operators. Java provides various operators for mathematical calculations, logical judgments, and more. This chapter systematically covers the concepts, classifications, precedence, and associativity of operators.
1. Operators and Operands
- Operator: A symbol that performs an operation (e.g.,
+,-,*,/,=) - Operand: The target of the operator's operation (variables, constants, literals, expressions)
int result = x + 3;
// Operators: = , +
// Operands: result, x, 3
An operator always returns a result value after performing an operation on its operands. The result can be stored in a variable or used as an operand for another operation.
public class OperatorBasic {
public static void main(String[] args) {
int x = 10;
int y = 3;
// + operator: stores the result (13) of adding x and y into sum
int sum = x + y;
// * operator: stores the result (26) of multiplying sum by 2 into product
int product = sum * 2;
// == operator: stores the result (true) of comparing x and 10 into isEqual
boolean isEqual = (x == 10);
System.out.println("sum = " + sum); // 13
System.out.println("product = " + product); // 26
System.out.println("isEqual = " + isEqual); // true
}
}
2. Classification of Operators
Java operators can be classified into three types based on the number of operands.
| Classification | Description | Example |
|---|---|---|
| Unary Operator | 1 operand | ++i, --i, -x, !flag |
| Binary Operator | 2 operands | a + b, x > y, a && b |
| Ternary Operator | 3 operands | condition ? trueValue : falseValue |
They can also be classified by function:
| Type | Operators | Description |
|---|---|---|
| Arithmetic | +, -, *, /, % | Four basic operations and remainder |
| Comparison | ==, !=, >, <, >=, <= | Size and equality comparison, result is boolean |
| Logical | &&, ||, !, ^ | Logical AND, OR, NOT, XOR |
| Assignment | =, +=, -=, *=, /=, %= | Store right-hand value into left-hand variable |
| Bitwise | &, |, ^, ~, <<, >>, >>> | Bit-level operations on binary numbers |
| Conditional | ? : | Ternary operator, selects value based on condition |
| Other | instanceof, ->, :: | Type check, lambda, method reference |
3. Operator Precedence
When multiple operators appear in an expression, this rule determines which operator is processed first. It is similar to mathematical order of operations (e.g., * before +).
The table below is sorted from highest to lowest precedence.
| Precedence | Operators | Associativity | Description |
|---|---|---|---|
| 1 (highest) | (), [], . | Left to right | Parentheses, array access, member access |
| 2 | ++, -- (postfix) | Left to right | Postfix increment/decrement |
| 3 | ++, -- (prefix), +, -, ~, ! | Right to left | Prefix increment/decrement, unary sign, bitwise NOT, logical NOT |
| 4 | *, /, % | Left to right | Multiplication, division, remainder |
| 5 | +, - | Left to right | Addition, subtraction |
| 6 | <<, >>, >>> | Left to right | Bit shift |
| 7 | <, >, <=, >=, instanceof | Left to right | Relational comparison, type check |
| 8 | ==, != | Left to right | Equality comparison |
| 9 | & | Left to right | Bitwise AND |
| 10 | ^ | Left to right | Bitwise XOR |
| 11 | | | Left to right | Bitwise OR |
| 12 | && | Left to right | Logical AND |
| 13 | || | Left to right | Logical OR |
| 14 | ? : | Right to left | Ternary (conditional) operator |
| 15 (lowest) | =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, >>>= | Right to left | Assignment operators |
public class Precedence {
public static void main(String[] args) {
// * has higher precedence than +, so it is calculated first
int result1 = 2 + 3 * 4; // 2 + 12 = 14
System.out.println(result1); // 14
// Use parentheses to specify precedence directly
int result2 = (2 + 3) * 4; // 5 * 4 = 20
System.out.println(result2); // 20
// Comparison operators have higher precedence than logical operators
boolean check = 5 > 3 && 10 < 20; // (5>3) && (10<20) = true && true = true
System.out.println(check); // true
}
}
You don't need to memorize the precedence table. In complex expressions, using parentheses () to explicitly specify precedence is a good habit that improves readability and reduces bugs.
4. Associativity
When multiple operators of equal precedence appear, this rule determines whether they are processed left-to-right or right-to-left.
Left-to-Right (Left Associativity)
Most binary operators are processed from left to right.
// Left associativity example: - operator
int a = 10 - 3 - 2;
// (10 - 3) - 2 = 7 - 2 = 5 (left to right)
System.out.println(a); // 5
// Left associativity example: / operator
int b = 24 / 4 / 2;
// (24 / 4) / 2 = 6 / 2 = 3 (left to right)
System.out.println(b); // 3
Right-to-Left (Right Associativity)
Unary operators, assignment operators, and ternary operators are processed from right to left.
// Right associativity example: assignment operator =
int x, y, z;
x = y = z = 10;
// z = 10 -> y = 10 -> x = 10 (right to left)
System.out.println(x + ", " + y + ", " + z); // 10, 10, 10
// Right associativity example: prefix unary operator
int n = 5;
int result = -(-n); // -(-(5)) = -(-5) = 5
System.out.println(result); // 5
5. Assignment Operators and Compound Assignment Operators
Simple Assignment Operator (=)
Stores the right-hand value into the left-hand variable. It is the most frequently used operator in Java.
int score = 100; // Store 100 into score
String name = "Alice"; // Store "Alice" into name
boolean pass = true; // Store true into pass
Compound Assignment Operators
Shorthand expressions that perform arithmetic and assignment at once.
| Compound | Equivalent | Description |
|---|---|---|
a += b | a = a + b | Add b to a and store in a |
a -= b | a = a - b | Subtract b from a and store in a |
a *= b | a = a * b | Multiply a by b and store in a |
a /= b | a = a / b | Divide a by b and store in a |
a %= b | a = a % b | Remainder of a divided by b, store in a |
a &= b | a = a & b | Bitwise AND then store in a |
a |= b | a = a | b | Bitwise OR then store in a |
a ^= b | a = a ^ b | Bitwise XOR then store in a |
a <<= b | a = a << b | Left shift then store in a |
a >>= b | a = a >> b | Right shift then store in a |
public class CompoundAssignment {
public static void main(String[] args) {
int score = 80;
score += 10; // score = score + 10 = 90
System.out.println("+=: " + score); // 90
score -= 5; // score = score - 5 = 85
System.out.println("-=: " + score); // 85
score *= 2; // score = score * 2 = 170
System.out.println("*=: " + score); // 170
score /= 4; // score = score / 4 = 42 (integer division, decimal truncated)
System.out.println("/=: " + score); // 42
score %= 10; // score = score % 10 = 2
System.out.println("%=: " + score); // 2
}
}
Compound assignment operators internally perform implicit casting.
byte b = 10;
// b = b + 5; // Compile error! b+5 result is int, cannot assign directly to byte
b += 5; // Works fine! Internally processed as b = (byte)(b + 5)
System.out.println(b); // 15
Even in cases where a simple assignment would require an explicit cast, compound assignment operators handle it automatically.
6. Precedence Pitfalls and Parentheses Recommendation
Misunderstanding precedence can produce unexpected results.
public class PrecedenceTrap {
public static void main(String[] args) {
// Trap 1: precedence of + and *
int a = 1 + 2 * 3; // 1 + (2*3) = 1 + 6 = 7 (OK if 7 was intended)
int b = (1 + 2) * 3; // (1+2) * 3 = 3 * 3 = 9 (must use parentheses if 9 was intended)
System.out.println("a = " + a); // 7
System.out.println("b = " + b); // 9
// Trap 2: bitwise and comparison operators
// & has LOWER precedence than ==!
int flags = 0b0110;
// Wrong: flags & 0b0010 == 0 -> flags & (0b0010 == 0) -> flags & false -> compile error
// Correct: use parentheses to make it explicit
boolean hasBit = (flags & 0b0010) != 0;
System.out.println("hasBit = " + hasBit); // true
// Trap 3: logical operators and assignment
int x = 5, y = 3;
boolean result = x > 0 && y > 0; // (x > 0) && (y > 0) -> true
System.out.println("result = " + result); // true
// Trap 4: string + operator order
System.out.println(1 + 2 + "3"); // "33" (1+2=3, 3+"3"="33")
System.out.println("1" + 2 + 3); // "123" ("1"+2="12", "12"+3="123")
System.out.println("1" + (2 + 3)); // "15" (parentheses add first)
}
}
The &, |, ^ operators have lower precedence than ==, !=. When comparing the result of a bitwise operation, always wrap it in parentheses to ensure intended behavior.
// Wrong
if (flags & MASK == 0) { ... } // Interpreted as flags & (MASK == 0)
// Correct
if ((flags & MASK) == 0) { ... } // Parentheses ensure bitwise op runs first
7. Practical Example: Complex Expression Calculation
The example below shows various operators used together through actual exam score processing and grade calculation.
public class ScoreCalculator {
public static void main(String[] args) {
// Subject scores
int korean = 85;
int english = 92;
int math = 78;
int science = 88;
int history = 76;
// Total calculation (arithmetic operators)
int total = korean + english + math + science + history;
// Average calculation (arithmetic + type casting)
double average = (double) total / 5;
// Highest score (nested ternary operator)
int maxScore = (korean > english) ? korean : english;
maxScore = (maxScore > math) ? maxScore : math;
maxScore = (maxScore > science) ? maxScore : science;
maxScore = (maxScore > history) ? maxScore : history;
// Pass/fail (comparison + logical operators)
boolean pass = (average >= 70.0) && (math >= 60);
// Bonus score (compound assignment operator)
double bonusAverage = average;
bonusAverage += 5.0; // +5 attendance bonus
// Grade determination (compound comparison)
String grade;
if (bonusAverage >= 90) {
grade = "A";
} else if (bonusAverage >= 80) {
grade = "B";
} else if (bonusAverage >= 70) {
grade = "C";
} else {
grade = "F";
}
// Output
System.out.println("===== Report Card =====");
System.out.println("Total: " + total);
System.out.printf("Average: %.2f%n", average);
System.out.printf("Bonus: %.2f%n", bonusAverage);
System.out.println("Highest: " + maxScore);
System.out.println("Result: " + (pass ? "Pass" : "Fail"));
System.out.println("Grade: " + grade);
}
}
Output:
===== Report Card =====
Total: 419
Average: 83.80
Bonus: 88.80
Highest: 92
Result: Pass
Grade: B
8. Key Summary
| Concept | Description |
|---|---|
| Operator | Symbol that performs an operation |
| Operand | Value or variable that is the target of an operation |
| Precedence | Processing order when multiple operators exist (higher = first) |
| Associativity | Direction of processing for operators at the same precedence level |
| Compound Assignment | +=, -=, etc. — perform operation and assignment at once |
- Use parentheses liberally when precedence is uncertain.
- Break complex arithmetic into multiple variables for easier debugging.
- Assignment operator chaining (
x = y = z = 0) should only be used for simple initialization.