An operator is a specialized symbol that instructs the compiler to execute specific mathematical, relational, or logical manipulations on one, two, or three operands.
Used to perform fundamental arithmetic operations:
| Operator | Description | Example (a = 15, b = 4) |
|---|---|---|
+ | Addition | a + b → 19 |
- | Subtraction | a - b → 11 |
* | Multiplication | a * b → 60 |
/ | Division (Integer truncates) | a / b → 3 (15 / 4 = 3) |
% | Modulus (Remainder) | a % b → 3 (15 % 4 = 3 remainder) |
Compare two operands and always yield a boolean result (true or false):
== (Equal to): 10 == 10 → true!= (Not equal to): 10 != 5 → true> and >= (Greater than / or equal): 15 >= 15 → true< and <= (Less than / or equal): 8 <= 12 → trueUsed to combine multiple boolean conditions:
int age = 22;
boolean hasLicense = true;
// Short-Circuit AND (&&): Both must be true
if (age >= 18 && hasLicense) {
System.out.println("Eligible to Drive!");
}
// Short-Circuit OR (||): At least one must be true
boolean hasPassport = false;
boolean hasVoterId = true;
if (hasPassport || hasVoterId) {
System.out.println("Identity Verified!");
}
// Logical NOT (!): Inverts boolean state
boolean isBlocked = false;
if (!isBlocked) {
System.out.println("Access Granted!");
}
A concise one-line alternative to simple if-else statements:
int marks = 78;
// Syntax: condition ? value_if_true : value_if_false
String result = (marks >= 40) ? "PASS" : "FAIL";
System.out.println("Student Status: " + result); // Output: PASS
When an expression contains multiple operators, precedence determines evaluation order:
| Precedence Level | Operators | Associativity |
|---|---|---|
| 1 (Highest) | Postfix: expr++, expr--, [], ., () |
Left to Right |
| 2 | Unary: ++expr, --expr, +, -, !, ~ |
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 | Logical AND: && |
Left to Right |
| 9 | Logical OR: || |
Left to Right |
| 10 | Ternary: ? : |
Right to Left |
| 11 (Lowest) | Assignment: =, +=, -=, *=, /=, %= |
Right to Left |
Exam Tracing Problem: "What is the output of the following Java snippet?"
int a = 5;
int b = a++ + ++a * 2;
System.out.println("a=" + a + ", b=" + b);
Step-by-Step Dry Run:
1. a++ yields 5 (and increments a to 6).
2. Next, ++a increments a from 6 to 7 and yields 7.
3. Multiplication has higher precedence than addition: 7 * 2 = 14.
4. Addition: 5 + 14 = 19.
Final Result: a=7, b=19.
Now let us explore Java comments and industry-standard Javadoc documentation. Proceed to: Java Comments & Javadoc Documentation →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Using operators in conditional logic.
Operator numeric promotion.
Multi-branch decision making.
Quick lookup table.