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.
1. Introduction to Java Operators
Operators perform calculations, comparisons, and logical tests on operands. Java supports arithmetic, relational, logical, bitwise, assignment, and ternary operators.
- Unary: ++, --, !
- Binary: +, -, *, /, %
- Relational: ==, !=, <, >, <=, >=
- Logical: &&, ||, !
public class OperatorIntro {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println(a + b);
System.out.println(a % b);
System.out.println(a > b);
}
}
2. Java Operators by Type
Each category below lists operators with their purpose and a short example. Use these tables as a quick reference while coding or preparing for interviews.
Arithmetic operators
| Operator | Purpose | Short example |
|---|---|---|
+ | Add two numeric values; also concatenates strings | sum = a + b; |
- | Subtract right operand from left | diff = a - b; |
* | Multiply two values | prod = a * b; |
/ | Divide left by right (integer division truncates) | quot = 7 / 2; → 3 |
% | Remainder after division (modulus) | rem = 7 % 3; → 1 |
Unary operators
| Operator | Purpose | Short example |
|---|---|---|
++ | Increment by 1 (prefix: before use; postfix: after) | count++; or ++count; |
-- | Decrement by 1 | count--; |
+ - | Unary plus / minus on a single value | int n = -x; |
! | Logical NOT — flips boolean value | if (!active) { ... } |
Relational (comparison) operators
| Operator | Purpose | Short example |
|---|---|---|
== | True if operands are equal | if (a == b) { ... } |
!= | True if operands are not equal | if (x != 0) { ... } |
< > | Less than / greater than | if (age > 18) { ... } |
<= >= | Less than or equal / greater than or equal | if (score >= 60) { ... } |
Logical operators
| Operator | Purpose | Short example |
|---|---|---|
&& | Logical AND — short-circuits if left is false | if (x > 0 && y > 0) { ... } |
|| | Logical OR — short-circuits if left is true | if (isAdmin || isOwner) { ... } |
! | Negate a boolean condition | while (!done) { ... } |
Bitwise operators
| Operator | Purpose | Short example |
|---|---|---|
& | Bitwise AND — each bit compared | int mask = a & 0xFF; |
| | Bitwise OR — set bits where either operand has 1 | flags |= PERM_READ; |
^ | Bitwise XOR — 1 where bits differ | toggle = x ^ 1; |
~ | Bitwise complement (flip all bits) | int inv = ~n; |
<< | Left shift — multiply by powers of 2 | int x = 1 << 3; → 8 |
>> | Signed right shift (sign bit preserved) | int y = 16 >> 2; → 4 |
>>> | Unsigned right shift (zero-fill left) | int z = -1 >>> 1; |
Assignment operators
| Operator | Purpose | Short example |
|---|---|---|
= | Assign value to variable | x = 10; |
+= | Add and assign | total += price; |
-= | Subtract and assign | balance -= fee; |
*= /= %= | Multiply, divide, or modulus then assign | count *= 2; |
&= |= ^= <<= >>= >>>= | Bitwise compound assignment | flags |= MASK; |
Ternary and other operators
| Operator | Purpose | Short example |
|---|---|---|
? : | Conditional — pick one of two values | max = (a > b) ? a : b; |
instanceof | Test whether an object is of a type | if (obj instanceof String) { ... } |
3. How Bitwise Operators Work (Positive & Negative)
Bitwise operators (&, |, ^, ~, <<, >>, >>>) work on the binary bits of int, long, byte, and short. In Java, signed integers use two's complement to represent negative numbers.
Positive numbers in binary
Non-negative values use normal binary: each bit is a power of two. Example with 8 bits (for clarity; int uses 32 bits):
Negative numbers — two's complement
To store -n: flip all bits of +n (one's complement), then add 1. Equivalently in Java: -n == ~n + 1 (for the same type).
| Decimal (8-bit view) | Binary | Notes |
|---|---|---|
+5 | 0000 0101 | Positive — leading bit 0 |
-5 | 1111 1011 | Negative — leading bit 1 in two's complement |
-1 | 1111 1111 | All bits set (for 8 bits) |
-128 | 1000 0000 | Smallest 8-bit signed value |
Bitwise AND (&) — positive and negative
Result bit is 1 only if both operands have 1 in that position.
Common use: value & 0xFF keeps the lowest 8 bits (works the same whether the high bits are 0 or 1).
Bitwise OR (|) and XOR (^)
Bitwise NOT (~)
Flips every bit. For signed integers, ~n == -(n + 1).
Left shift (<<) — positive and negative
Shifts bits left; vacated right bits are filled with 0. For non-negative values, n << k is like multiplying by 2^k (until overflow).
Right shift — signed (>>) vs unsigned (>>>)
This is where positive and negative behave differently.
| Operator | Left vacated bits | Typical use |
|---|---|---|
>> | Copy the sign bit (arithmetic shift) | Signed int — preserves sign |
>>> | Fill with 0 (logical shift) | Treat bits as unsigned; clear high bits |
Remember
>> keeps the number “looking” negative when it started negative. >>> does not — use it when you want to zero-fill the left, e.g. extracting an unsigned byte from an int: (byteVal & 0xFF) or intVal >>> 8.
public class BitwiseSignedDemo {
public static void main(String[] args) {
int a = 12, b = 10;
System.out.println("12 & 10 = " + (a & b)); // 8
System.out.println("12 | 10 = " + (a | b)); // 14
System.out.println("12 ^ 10 = " + (a ^ b)); // 6
int n = 5;
System.out.println("~5 = " + (~n)); // -6
System.out.println("5 << 2 = " + (n << 2)); // 20
int neg = -8;
System.out.println("-8 >> 1 = " + (neg >> 1)); // -4
System.out.println("-8 >>> 1 = " + (neg >>> 1)); // 2147483644
int mask = -1;
System.out.println("-1 >> 1 = " + (mask >> 1)); // -1
System.out.println("-1 >>> 1 = " + (mask >>> 1)); // 2147483647
// Two's complement check
System.out.println("-5 in binary (32-bit): " + Integer.toBinaryString(-5));
System.out.println("~5 + 1 = " + ((~5) + 1)); // -5
}
}
4. Operator Precedence and Associativity
When multiple operators appear in one expression, precedence determines evaluation order. Use parentheses to make intent explicit and avoid subtle bugs.
- Multiplication before addition
- Relational before logical AND
- Assignment has low precedence
- Most operators associate left-to-right
public class PrecedenceDemo {
public static void main(String[] args) {
int result = 2 + 3 * 4;
System.out.println(result);
System.out.println((2 + 3) * 4);
}
}
5. Operator Examples
Short-circuit logical operators (&& and ||) skip the right operand when the result is already determined. This prevents null pointer errors in chained conditions.
- Use && instead of & for boolean logic
- Prefix ++i increments before use
- Compound assignment: x += 5
- String + concatenates text
public class LogicDemo {
public static void main(String[] args) {
String name = null;
if (name != null && name.length() > 0) {
System.out.println(name);
} else {
System.out.println("No name");
}
}
}
6. Operators Best Practices
Clear expressions reduce bugs in interviews and production code. Prefer readability over clever one-liners.
- Use parentheses for complex expressions
- Avoid mixing ++ with other operators in one line
- Compare strings with equals(), not ==
- Use Math methods for advanced math
- Watch integer division truncation
7. Tricky Points
Common operator pitfalls in Java interviews and real code — grouped by operator type.
Arithmetic
7 / 2 is 3, not 3.5. Cast at least one operand: 7.0 / 2 or (double) 7 / 2.
-7 % 3 is -1 in Java (sign of dividend), not 2.
"Score: " + 5 + 10 prints Score: 510 because + is left-associative string concatenation after the first +.
Unary and increment
int x = 5; int y = x++; leaves x == 6 and y == 5. With ++x, both become 6 before assignment.
a[i++] = i; — evaluation order is hard to read and easy to get wrong.
Relational and logical
if (x = 5) assigns; if (x == 5) compares. A common typo in C-style languages.
"a" == "a" may be true (pool), but new String("a") == new String("a") is false. Use equals().
obj != null && obj.length() > 0, length() is never called if obj is null. With & (bitwise AND on booleans), both sides always run — risk of NullPointerException.
Bitwise
& is bitwise AND (or non-short-circuit boolean AND). && is logical AND with short-circuit — use && in conditions.
int (shift by 32 is same as shift by 0).
Assignment, ternary, and precedence
a += b * c means a = a + (b * c), not (a + b) * c.
a > b ? x : c > d ? y : z is legal but hard to read — use parentheses or if-else.
2 + 3 * 4 is 14, not 20. When in doubt, add parentheses.
Rule of thumb
Use parentheses for clarity; equals() for strings; && / || for conditions; cast for real division; avoid clever ++ in the same expression as other uses of the variable.