Java Operators - Complete Guide
Master all Java operators with detailed explanations, usage examples, and operator precedence rules. Operators are special symbols that perform operations on variables and values.
7 Operator Types
Comprehensive Coverage
Precedence Levels
Order of Evaluation
Practical Examples
Real-world Usage
1. What are Java Operators?
Operators in Java are special symbols that tell the compiler to perform specific mathematical, relational, or logical operations and produce results. They are the building blocks of expressions in Java programming.
Operator Characteristics
- Operators work on operands (variables/values)
- Different operators have different precedence
- Most operators are left-to-right associative
- Some operators can be overloaded in Java
- Operators can be unary, binary, or ternary
- Java supports both primitive and object operations
Operator Categories
- Arithmetic: +, -, *, /, %
- Relational: ==, !=, >, <, >=, <=
- Logical: &&, ||, !
- Bitwise: &, |, ^, ~, <<, >>, >>>
- Assignment: =, +=, -=, *=, /=
- Ternary: ? : (conditional operator)
- Misc: instanceof, new, . (dot)
Quick Reference: Common Java Operators
Here are the most frequently used Java operators:
2. Complete Java Operators Reference Table
This comprehensive table lists all Java operators with their type, description, example, and precedence:
| Operator | Name | Description | Example | Precedence |
|---|---|---|---|---|
+ |
Addition | Adds two operands | a + b |
4 |
- |
Subtraction | Subtracts right operand from left | a - b |
4 |
* |
Multiplication | Multiplies two operands | a * b |
3 |
/ |
Division | Divides left operand by right | a / b |
3 |
% |
Modulus | Returns remainder of division | a % b |
3 |
++ |
Increment | Increases value by 1 (prefix/postfix) | a++ or ++a |
2 |
-- |
Decrement | Decreases value by 1 (prefix/postfix) | a-- or --a |
2 |
| Operator | Name | Description | Example | Precedence |
|---|---|---|---|---|
== |
Equal to | Checks if two values are equal | a == b |
7 |
!= |
Not equal to | Checks if two values are not equal | a != b |
7 |
> |
Greater than | Checks if left is greater than right | a > b |
6 |
< |
Less than | Checks if left is less than right | a < b |
6 |
>= |
Greater than or equal | Checks if left is greater than or equal to right | a >= b |
6 |
<= |
Less than or equal | Checks if left is less than or equal to right | a <= b |
6 |
| Operator | Name | Description | Example | Precedence |
|---|---|---|---|---|
&& |
Logical AND | Returns true if both conditions are true | a && b |
11 |
|| |
Logical OR | Returns true if at least one condition is true | a || b |
12 |
! |
Logical NOT | Reverses the logical state | !a |
2 |
& |
Boolean AND | Always evaluates both operands | a & b |
8 |
| |
Boolean OR | Always evaluates both operands | a | b |
10 |
^ |
Boolean XOR | Returns true if operands are different | a ^ b |
9 |
| Operator | Name | Description | Example | Equivalent to |
|---|---|---|---|---|
= |
Assignment | Assigns right operand to left | a = b |
a = b |
+= |
Add and assign | Adds then assigns | a += b |
a = a + b |
-= |
Subtract and assign | Subtracts then assigns | a -= b |
a = a - b |
*= |
Multiply and assign | Multiplies then assigns | a *= b |
a = a * b |
/= |
Divide and assign | Divides then assigns | a /= b |
a = a / b |
%= |
Modulus and assign | Modulus then assigns | a %= b |
a = a % b |
&= |
AND and assign | Bitwise AND then assigns | a &= b |
a = a & b |
|= |
OR and assign | Bitwise OR then assigns | a |= b |
a = a | b |
^= |
XOR and assign | Bitwise XOR then assigns | a ^= b |
a = a ^ b |
| Operator | Name | Description | Example | Precedence |
|---|---|---|---|---|
& |
Bitwise AND | Sets each bit to 1 if both bits are 1 | a & b |
8 |
| |
Bitwise OR | Sets each bit to 1 if either bit is 1 | a | b |
10 |
^ |
Bitwise XOR | Sets each bit to 1 if only one bit is 1 | a ^ b |
9 |
~ |
Bitwise NOT | Inverts all the bits (unary) | ~a |
2 |
<< |
Left shift | Shifts bits left, padding with zeros | a << 2 |
5 |
>> |
Right shift | Shifts bits right, preserves sign | a >> 2 |
5 |
>>> |
Unsigned right shift | Shifts bits right, pads with zeros | a >>> 2 |
5 |
| Operator | Name | Description | Example | Precedence |
|---|---|---|---|---|
? : |
Ternary/Conditional | Shorthand for if-else statement | a ? b : c |
13 |
instanceof |
Type Comparison | Checks if object is instance of class | obj instanceof String |
7 |
. |
Dot Operator | Accesses members of class/object | obj.method() |
1 |
new |
Object Creation | Creates new objects | new String() |
2 |
(type) |
Type Cast | Casts object to different type | (int) 3.14 |
2 |
- 1-4: Highest precedence (Parentheses, Dot, new, cast)
- 5-7: Medium precedence (Arithmetic, Shift, Relational)
- 8-12: Lower precedence (Bitwise, Logical)
- 13-14: Lowest precedence (Ternary, Assignment)
- Tip: Use parentheses
()to explicitly control precedence
3. Operator Precedence and Associativity
Operator precedence determines the order in which operators are evaluated in expressions. When operators have the same precedence, associativity determines the order.
Java Operator Precedence Table (Highest to Lowest)
| Precedence | Operator | Description | Associativity |
|---|---|---|---|
| 1 | () [] . |
Parentheses, Array access, Member access | Left to Right |
| 2 | ++ -- + - ~ ! (type) new |
Unary operators, Cast, Object creation | Right to Left |
| 3 | * / % |
Multiplicative | Left to Right |
| 4 | + - |
Additive | Left to Right |
| 5 | << >> >>> |
Shift | Left to Right |
| 6 | < <= > >= instanceof |
Relational, Type comparison | Left to Right |
| 7 | == != |
Equality | Left to Right |
| 8 | & |
Bitwise AND | Left to Right |
| 9 | ^ |
Bitwise XOR | Left to Right |
| 10 | | |
Bitwise OR | Left to Right |
| 11 | && |
Logical AND | Left to Right |
| 12 | || |
Logical OR | Left to Right |
| 13 | ? : |
Ternary conditional | Right to Left |
| 14 | = += -= *= /= etc. |
Assignment operators | Right to Left |
public class PrecedenceExample {
public static void main(String[] args) {
int a = 10, b = 5, c = 2;
// Without parentheses (default precedence)
int result1 = a + b * c; // 10 + (5 * 2) = 20
System.out.println("a + b * c = " + result1);
// With parentheses (explicit precedence)
int result2 = (a + b) * c; // (10 + 5) * 2 = 30
System.out.println("(a + b) * c = " + result2);
// Complex expression
boolean result3 = a > b && b < c || a == 10;
// Equivalent to: ((a > b) && (b < c)) || (a == 10)
System.out.println("a > b && b < c || a == 10 = " + result3);
// Assignment precedence (right to left)
int x, y, z;
x = y = z = 100; // All variables get value 100
System.out.println("x=" + x + ", y=" + y + ", z=" + z);
// Ternary operator precedence
String message = a > b ? "Greater" : "Less or Equal";
System.out.println("Ternary result: " + message);
}
}
4. Important Operators with Detailed Examples
Here are detailed examples of some of the most important Java operators in action:
Arithmetic Operators Example
Arithmetic operators perform basic mathematical operations on numeric values.
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 20, b = 7;
// Basic arithmetic operations
System.out.println("a = " + a + ", b = " + b);
System.out.println("a + b = " + (a + b)); // Addition: 27
System.out.println("a - b = " + (a - b)); // Subtraction: 13
System.out.println("a * b = " + (a * b)); // Multiplication: 140
System.out.println("a / b = " + (a / b)); // Division: 2 (integer division)
System.out.println("a % b = " + (a % b)); // Modulus: 6
// Floating point division
double x = 20.0, y = 7.0;
System.out.println("\nFloating point division:");
System.out.println("x / y = " + (x / y)); // 2.857142857142857
// Increment and decrement operators
int counter = 5;
System.out.println("\nIncrement/Decrement:");
System.out.println("Original counter: " + counter);
System.out.println("Post-increment (counter++): " + (counter++)); // 5
System.out.println("After post-increment: " + counter); // 6
System.out.println("Pre-increment (++counter): " + (++counter)); // 7
System.out.println("After pre-increment: " + counter); // 7
// Compound assignment operators
int total = 10;
total += 5; // total = total + 5
System.out.println("\nAfter total += 5: " + total); // 15
total *= 2; // total = total * 2
System.out.println("After total *= 2: " + total); // 30
total %= 7; // total = total % 7
System.out.println("After total %= 7: " + total); // 2
}
}
Logical and Relational Operators Example
Logical and relational operators are used for decision making and flow control.
public class LogicalOperators {
public static void main(String[] args) {
int age = 25;
boolean hasLicense = true;
int score = 85;
// Relational operators
System.out.println("Age comparisons:");
System.out.println("age > 18: " + (age > 18)); // true
System.out.println("age < 21: " + (age < 21)); // false
System.out.println("age >= 25: " + (age >= 25)); // true
System.out.println("age <= 30: " + (age <= 30)); // true
System.out.println("age == 25: " + (age == 25)); // true
System.out.println("age != 30: " + (age != 30)); // true
// Logical operators
System.out.println("\nLogical operations:");
System.out.println("Can drive? " + (age >= 18 && hasLicense)); // true
System.out.println("Is teenager or senior? " +
((age >= 13 && age <= 19) || age >= 65)); // false
boolean isPassing = score >= 60;
boolean isExcellent = score >= 90;
System.out.println("\nScore analysis:");
System.out.println("Score: " + score);
System.out.println("Is passing: " + isPassing); // true
System.out.println("Is excellent: " + isExcellent); // false
System.out.println("Is good but not excellent: " +
(isPassing && !isExcellent)); // true
// Short-circuit evaluation
System.out.println("\nShort-circuit evaluation:");
boolean result = (score > 100) && (someMethod()); // someMethod() not called
System.out.println("Result: " + result);
// Ternary operator
String grade = score >= 90 ? "A" :
score >= 80 ? "B" :
score >= 70 ? "C" :
score >= 60 ? "D" : "F";
System.out.println("\nGrade: " + grade); // B
}
static boolean someMethod() {
System.out.println("This method was called");
return true;
}
}
Bitwise Operators Example
Bitwise operators work on individual bits of integer types.
public class BitwiseOperators {
public static void main(String[] args) {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
System.out.println("a = " + a + " (Binary: " + Integer.toBinaryString(a) + ")");
System.out.println("b = " + b + " (Binary: " + Integer.toBinaryString(b) + ")");
// Bitwise AND
int andResult = a & b; // 0101 & 0011 = 0001 (1 in decimal)
System.out.println("\na & b = " + andResult +
" (Binary: " + Integer.toBinaryString(andResult) + ")");
// Bitwise OR
int orResult = a | b; // 0101 | 0011 = 0111 (7 in decimal)
System.out.println("a | b = " + orResult +
" (Binary: " + Integer.toBinaryString(orResult) + ")");
// Bitwise XOR
int xorResult = a ^ b; // 0101 ^ 0011 = 0110 (6 in decimal)
System.out.println("a ^ b = " + xorResult +
" (Binary: " + Integer.toBinaryString(xorResult) + ")");
// Bitwise NOT (complement)
int notResult = ~a; // ~0101 = 11111111111111111111111111111010
System.out.println("~a = " + notResult +
" (Binary: " + Integer.toBinaryString(notResult) + ")");
// Left shift (multiply by 2^n)
int leftShift = a << 1; // 0101 << 1 = 1010 (10 in decimal)
System.out.println("\na << 1 = " + leftShift +
" (Binary: " + Integer.toBinaryString(leftShift) + ")");
// Right shift (divide by 2^n, preserves sign)
int rightShift = a >> 1; // 0101 >> 1 = 0010 (2 in decimal)
System.out.println("a >> 1 = " + rightShift +
" (Binary: " + Integer.toBinaryString(rightShift) + ")");
// Unsigned right shift (pads with 0)
int negative = -8; // Binary: 11111111111111111111111111111000
int unsignedShift = negative >>> 1;
System.out.println("\n-8 >>> 1 = " + unsignedShift +
" (Binary: " + Integer.toBinaryString(unsignedShift) + ")");
// Practical example: Checking if number is even/odd
int number = 42;
boolean isEven = (number & 1) == 0; // Last bit 0 = even, 1 = odd
System.out.println("\n" + number + " is even: " + isEven);
}
}
5. Common Mistakes and Best Practices
- Confusing = with ==:
if (x = 5)❌ (useif (x == 5)✅) - Integer division:
5 / 2 = 2❌ (use5.0 / 2 = 2.5✅) - Precedence errors:
a + b * cvs(a + b) * c - Increment/decrement timing:
result = x++ + ++x(confusing) - Floating point comparison:
0.1 + 0.2 == 0.3❌ (false due to precision) - Null pointer with . operator:
obj.method()when obj is null
Best Practices
- Use parentheses for clarity even when not required
- Use
&&and||instead of&and|for boolean logic - Use compound assignment operators for brevity
- Be careful with integer division vs floating point division
- Use
Math.abs()for absolute value instead of bit tricks - Prefer readability over clever bitwise operations
Performance Tips
- Bitwise operations are faster than arithmetic for some tasks
x * 2can bex << 1for integersx / 2can bex >> 1for positive integers- Use
++iinstead ofi++in loops when possible - Avoid unnecessary type casting in tight loops
- Use final variables for constants to enable optimizations
public class OperatorBestPractices {
public static void main(String[] args) {
// GOOD: Use parentheses for clarity
int result1 = (a + b) * (c - d); // Clear precedence
// GOOD: Use compound assignment
total += amount; // Instead of: total = total + amount;
// GOOD: Handle floating point comparison properly
double a = 0.1;
double b = 0.2;
double sum = a + b;
// BAD: if (sum == 0.3) // Might fail due to precision
// GOOD: Use tolerance
double tolerance = 0.000001;
if (Math.abs(sum - 0.3) < tolerance) {
System.out.println("Sum is approximately 0.3");
}
// GOOD: Use && and || for boolean operations
boolean isValid = (age >= 18) && (hasLicense);
// GOOD: Clear increment usage
for (int i = 0; i < 10; ++i) { // Pre-increment is fine here
System.out.println(i);
}
// GOOD: Ternary for simple conditions
String status = (score >= 50) ? "Pass" : "Fail";
// GOOD: Use bitwise only when appropriate
boolean isEven = (number & 1) == 0; // Clear and efficient
}
}