Operators — Arithmetic, Relational, Logical, Bitwise, Assignment, and Precedence
In this tutorial, you will learn about Operators. We cover key concepts, practical examples, and best practices to help you master this topic.
Java operators are symbols that perform operations on operands, ranging from basic arithmetic to bitwise manipulation. Operators define how values are combined, compared, and transformed — they are the verbs of any programming language. Java provides over 40 operators organized into six categories.
What You'll Learn
- All operator categories with examples
- Short-circuit evaluation with logical operators
- Bitwise operations and their practical applications
- Operator precedence and associativity
Why It Matters
Misunderstanding operator precedence leads to subtle bugs that compilers do not catch. For example, x << 2 + 1 does not shift x by 2 and add 1 — it shifts by 3 because + has higher precedence than <<.
Real-World Use
Bitwise operators are essential for low-level programming (network protocols, image processing, flags). Relational and logical operators drive every conditional and loop in enterprise applications.
Arithmetic Operators
| Operator | Meaning | Example |
|---|---|---|
+ |
Addition | 5 + 3 = 8 |
- |
Subtraction | 5 - 3 = 2 |
* |
Multiplication | 5 * 3 = 15 |
/ |
Division | 5 / 2 = 2 (integer truncation) |
% |
Modulus (remainder) | 5 % 2 = 1 |
++ |
Increment | x++ or ++x |
-- |
Decrement | x-- or --x |
Integer Division Trap
int result = 5 / 2;
System.out.println(result); // 2, not 2.5
Integer division truncates toward zero. Use double if you need fractional results.
Increment/Decrement: Prefix vs Postfix
int a = 5;
int b = ++a; // a becomes 6, b = 6 (prefix: increment then use)
int c = a++; // c = 6, a becomes 7 (postfix: use then increment)
int x = 5;
System.out.println(x++); // prints 5, x becomes 6
System.out.println(++x); // prints 7, x becomes 7
Relational Operators
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal to |
< |
Less than |
> |
Greater than |
<= |
Less than or equal |
>= |
Greater than or equal |
Relational operators always produce a boolean result.
int age = 18;
boolean canVote = age >= 18; // true
boolean isMinor = age < 18; // false
Logical Operators
| Operator | Meaning |
|----------|---------|
| && | Short-circuit AND |
| || | Short-circuit OR |
| ! | NOT |
| & | Non-short-circuit AND |
| | | Non-short-circuit OR |
| ^ | XOR |
Short-Circuit Evaluation
String name = null;
if (name != null && name.length() > 0) { // safe: short-circuit prevents NPE
System.out.println("Name has " + name.length() + " chars");
}
With &&, if the left operand is false, the right operand is never evaluated. This prevents NullPointerException above.
Use & and | (non-short-circuit) when you need both sides evaluated regardless:
boolean result = hasPermission() & logAccess(); // both called even if hasPermission is false
Bitwise Operators
| Operator | Meaning | Example |
|----------|---------|---------|
| & | Bitwise AND | 5 & 3 = 1 (0101 & 0011 = 0001) |
| | | Bitwise OR | 5 | 3 = 7 (0101 | 0011 = 0111) |
| ^ | Bitwise XOR | 5 ^ 3 = 6 (0101 ^ 0011 = 0110) |
| ~ | Bitwise complement | ~5 = -6 (inverts all bits) |
| << | Left shift | 5 << 1 = 10 (multiply by 2) |
| >> | Signed right shift | -8 >> 2 = -2 (divide by 2, preserve sign) |
| >>> | Unsigned right shift | -8 >>> 2 = 1073741822 (zero-fill) |
Practical: Check if a Number is Even or Odd
int num = 42;
boolean isEven = (num & 1) == 0; // fast: checks least significant bit
Practical: Set, Clear, Toggle, and Check Bits
int flags = 0;
flags |= 1 << 2; // set bit 2: flags = 0000...0100
flags &= ~(1 << 2); // clear bit 2
boolean isSet = (flags & (1 << 2)) != 0; // check bit 2
flags ^= 1 << 2; // toggle bit 2
Assignment Operators
| Operator | Equivalent to |
|----------|---------------|
| = | x = y |
| += | x = x + y |
| -= | x = x - y |
| *= | x = x * y |
| /= | x = x / y |
| %= | x = x % y |
| &= | x = x & y |
| |= | x = x | y |
| ^= | x = x ^ y |
| <<= | x = x << y |
| >>= | x = x >> y |
| >>>= | x = x >>> y |
Compound assignment operators also include an implicit cast:
byte b = 10;
b = b + 5; // COMPILE ERROR: int cannot be converted to byte
b += 5; // OK: equivalent to b = (byte)(b + 5)
Ternary Operator
The ternary operator (?:) is a compact if-else:
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
Nested ternaries are possible but harm readability:
String result = (a > b) ? "a > b" : (a < b) ? "a < b" : "equal";
Operator Precedence
Operators with higher precedence are evaluated first. From highest to lowest:
| Precedence | Operators |
|------------|-----------|
| 1 (highest) | () [] . |
| 2 | ++ -- + - ~ ! (unary) |
| 3 | * / % |
| 4 | + - |
| 5 | << >> >>> |
| 6 | < > <= >= instanceof |
| 7 | == != |
| 8 | & |
| 9 | ^ |
| 10 | | |
| 11 | && |
| 12 | || |
| 13 | ?: (ternary) |
| 14 | = += -= etc. |
Surprising Precedence Examples
int x = 2;
int y = x++ * 3 + 2; // postfix ++ has high precedence, but it's "use then increment"
// y = 2 * 3 + 2 = 8, x becomes 3
int a = 10;
int b = a << 2 + 1; // WARNING: + has higher precedence than <<
// Actually: a << (2+1) = 10 << 3 = 80, not (10 << 2) + 1 = 41
Common Mistakes
- Using
=instead of==in conditions.if (x = 5)assigns 5 to x and evaluates to 5 (truthy) — but Java requiresboolean, so this is a compile error. In C/C++ it is a logic bug. - Forgetting integer division truncation.
double ratio = 1/2gives0.0, not0.5. Write1.0/2or(double)1/2. - Assuming
&&and&are interchangeable.&does not short-circuit. If the left side is false,&still evaluates the right side. - Confusing
x++with++xin complex expressions. Always test increment behavior in isolation if unsure. - Applying
>>instead of>>>for unsigned shift. For negative numbers,>>preserves the sign bit;>>>shifts in zeros.
Practice Questions
1. What is the value of -5 % 2 in Java?
-1. In Java, the sign of the modulus result follows the sign of the dividend.
2. Why does 5 / 2 equal 2 and not 2.5?
Both operands are integers, so Java performs integer division, truncating the fractional part.
3. What is the difference between && and &?
&& short-circuits: if the left operand is false, the right is not evaluated. & always evaluates both sides. & also serves as a bitwise AND operator.
4. What does 3 << 2 evaluate to?
12. 3 << 2 shifts the binary 0011 left by 2 positions, yielding 1100 (12). This is equivalent to multiplying 3 by 2^2.
5. What is -1 >>> 1?
2147483647 (Integer.MAX_VALUE). >>> shifts in zeros from the left, turning the sign bit to 0.
Challenge Question:
Write a program that uses bitwise operators to count the number of 1 bits in an int (popcount). Implement this without using Integer.bitCount(). Test it on 0, -1, Integer.MAX_VALUE, and 0b10101010.
FAQ
Mini Project
Write a program OperatorPlayground.java that:
- Demonstrates all arithmetic operators, including prefix vs postfix increment
- Shows integer division truncation with
5/2and5/2.0 - Implements a bit flag system for user permissions (READ = 1, WRITE = 2, EXECUTE = 4) using bitwise OR to combine permissions, AND to check, and XOR to toggle
- Prints truth tables for
&&,||,!, and^on booleans - Creates a nested ternary expression that converts a 0-100 grade to a letter grade (A, B, C, D, F)
Run each section with labeled output.
What's Next
Operators let you build expressions, but expressions need structure to make decisions. Lesson 6 covers control flow — if, else, switch expressions, the ternary operator for conditional assignment, and Java's evolving pattern matching capabilities.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro