Java Notes
Complete guide to all Java operators — arithmetic, relational, logical, bitwise, assignment, unary, ternary, and instanceof operators with examples, precedence table, and common pitfalls.
Operators are special symbols that perform operations on operands (variables and values). Java provides a rich set of operators for arithmetic, comparison, logic, bit manipulation, and more.
Categories of Java Operators
| Category | Operators | Purpose | ||
|---|---|---|---|---|
| Arithmetic | +, -, *, /, % | Mathematical calculations | ||
| Unary | +, -, ++, --, !, ~ | Single operand operations | ||
| Assignment | =, +=, -=, *=, /=, %= | Assign values | ||
| Relational | ==, !=, >, <, >=, <= | Compare values | ||
| Logical | &&, ` | , !` | Boolean logic | |
| Bitwise | &, ` | , ^, ~, <<, >>, >>>` | Bit manipulation | |
| Ternary | ? : | Conditional expression | ||
| instanceof | instanceof | Type checking |
1. Arithmetic Operators
public class ArithmeticOperators {
public static void main(String[] args) {
int a = 17, b = 5;
System.out.println("a = " + a + ", b = " + b);
System.out.println("─".repeat(30));
System.out.println("a + b = " + (a + b)); // Addition: 22
System.out.println("a - b = " + (a - b)); // Subtraction: 12
System.out.println("a * b = " + (a * b)); // Multiplication: 85
System.out.println("a / b = " + (a / b)); // Integer Division: 3 (truncated!)
System.out.println("a % b = " + (a % b)); // Modulus (remainder): 2
System.out.println("\n=== Integer Division vs Floating Division ===");
System.out.println("17 / 5 = " + (17 / 5)); // 3 (both int → int result)
System.out.println("17.0 / 5 = " + (17.0 / 5)); // 3.4 (double involved → double)
System.out.println("17 / 5.0 = " + (17 / 5.0)); // 3.4
System.out.println("(double)17 / 5 = " + ((double)17 / 5)); // 3.4
System.out.println("\n=== Modulus Uses ===");
// Check even/odd
int num = 42;
System.out.println(num + " is " + (num % 2 == 0 ? "even" : "odd"));
// Extract last digit
System.out.println("Last digit of 12345: " + (12345 % 10));
// Wrap around (circular)
int hours = 25;
System.out.println(hours + " hours in 12h format: " + (hours % 12));
}
}a = 17, b = 5 ────────────────────────────────── a + b = 22 a - b = 12 a * b = 85 a / b = 3 a % b = 2 === Integer Division vs Floating Division === 17 / 5 = 3 17.0 / 5 = 3.4 17 / 5.0 = 3.4 (double)17 / 5 = 3.4 === Modulus Uses === 42 is even Last digit of 12345: 5 25 hours in 12h format: 1
2. Unary Operators
+x = 10 -x = -10 === Pre vs Post Increment === a = 5 a++ = 5 a now = 6 ++a = 7 a now = 7 b = 10 b-- = 10 b now = 9 --b = 8 !true = false !false = true ~5 = -6
3. Relational (Comparison) Operators
public class RelationalOperators {
public static void main(String[] args) {
int a = 10, b = 20, c = 10;
System.out.println("a=" + a + ", b=" + b + ", c=" + c);
System.out.println("─".repeat(30));
System.out.println("a == b: " + (a == b)); // false
System.out.println("a == c: " + (a == c)); // true
System.out.println("a != b: " + (a != b)); // true
System.out.println("a > b: " + (a > b)); // false
System.out.println("a < b: " + (a < b)); // true
System.out.println("a >= c: " + (a >= c)); // true
System.out.println("a <= b: " + (a <= b)); // true
// CAUTION with reference comparison
System.out.println("\n=== Reference Comparison ===");
String s1 = new String("Hello");
String s2 = new String("Hello");
String s3 = s1;
System.out.println("s1 == s2: " + (s1 == s2)); // false (different objects!)
System.out.println("s1 == s3: " + (s1 == s3)); // true (same reference)
System.out.println("s1.equals(s2): " + s1.equals(s2)); // true (same content)
}
}a=10, b=20, c=10 ────────────────────────────────── a == b: false a == c: true a != b: true a > b: false a < b: true a >= c: true a <= b: true === Reference Comparison === s1 == s2: false s1 == s3: true s1.equals(s2): true
4. Logical Operators
a = true, b = false ────────────────────────────────── a && b: false a && a: true a || b: true b || b: false !a: false !b: true === Short-Circuit Behavior === x is between 0 and 10 String is null or empty (no NPE thanks to &&) Can drive: true
5. Assignment Operators
public class AssignmentOperators {
public static void main(String[] args) {
int a = 10;
System.out.println("Initial a = " + a);
a += 5; // a = a + 5 → 15
System.out.println("a += 5 → " + a);
a -= 3; // a = a - 3 → 12
System.out.println("a -= 3 → " + a);
a *= 2; // a = a * 2 → 24
System.out.println("a *= 2 → " + a);
a /= 4; // a = a / 4 → 6
System.out.println("a /= 4 → " + a);
a %= 4; // a = a % 4 → 2
System.out.println("a %= 4 → " + a);
// Bitwise assignment operators
int b = 12; // binary: 1100
b <<= 2; // left shift by 2: 110000 = 48
System.out.println("\n12 <<= 2 → " + b);
b >>= 1; // right shift by 1: 11000 = 24
System.out.println("48 >>= 1 → " + b);
// Compound assignment includes implicit cast!
byte x = 10;
x += 5; // OK! equivalent to: x = (byte)(x + 5);
// x = x + 5; // ERROR without cast! (x+5 is int)
System.out.println("\nbyte x += 5 → " + x);
}
}Initial a = 10 a += 5 → 15 a -= 3 → 12 a *= 2 → 24 a /= 4 → 6 a %= 4 → 2 12 <<= 2 → 48 48 >>= 1 → 24 byte x += 5 → 15
6. Ternary Operator
public class TernaryOperator {
public static void main(String[] args) {
// Syntax: condition ? valueIfTrue : valueIfFalse
int age = 20;
String status = (age >= 18) ? "Adult" : "Minor";
System.out.println(age + " → " + status); // Adult
// Nested ternary (use sparingly!)
int score = 75;
String grade = (score >= 90) ? "A" :
(score >= 80) ? "B" :
(score >= 70) ? "C" :
(score >= 60) ? "D" : "F";
System.out.println("Score " + score + " → Grade " + grade);
// Finding max of two numbers
int a = 15, b = 23;
int max = (a > b) ? a : b;
System.out.println("Max of " + a + " and " + b + " = " + max);
// Absolute value
int num = -7;
int abs = (num >= 0) ? num : -num;
System.out.println("|" + num + "| = " + abs);
}
}20 → Adult Score 75 → Grade C Max of 15 and 23 = 23 |-7| = 7
7. Bitwise Operators
public class BitwiseOperators {
public static void main(String[] args) {
int a = 12; // binary: 1100
int b = 10; // binary: 1010
System.out.println("a = 12 (1100)");
System.out.println("b = 10 (1010)");
System.out.println("─".repeat(30));
// AND — 1 only if both bits are 1
System.out.println("a & b = " + (a & b) + " (" +
Integer.toBinaryString(a & b) + ")"); // 8 (1000)
// OR — 1 if either bit is 1
System.out.println("a | b = " + (a | b) + " (" +
Integer.toBinaryString(a | b) + ")"); // 14 (1110)
// XOR — 1 if bits are different
System.out.println("a ^ b = " + (a ^ b) + " (" +
Integer.toBinaryString(a ^ b) + ")"); // 6 (0110)
// Left shift — multiply by 2^n
System.out.println("a << 1 = " + (a << 1)); // 24 (11000) — 12×2
System.out.println("a << 2 = " + (a << 2)); // 48 (110000) — 12×4
// Right shift — divide by 2^n
System.out.println("a >> 1 = " + (a >> 1)); // 6 (110) — 12/2
System.out.println("a >> 2 = " + (a >> 2)); // 3 (11) — 12/4
// Practical: Check if number is odd using bitwise AND
int num = 7;
boolean isOdd = (num & 1) == 1;
System.out.println("\n" + num + " is odd: " + isOdd);
// Swap without temp variable using XOR
int x = 5, y = 3;
System.out.println("\nBefore swap: x=" + x + ", y=" + y);
x = x ^ y;
y = x ^ y;
x = x ^ y;
System.out.println("After swap: x=" + x + ", y=" + y);
}
}a = 12 (1100) b = 10 (1010) ────────────────────────────────── a & b = 8 (1000) a | b = 14 (1110) a ^ b = 6 (110) a << 1 = 24 a << 2 = 48 a >> 1 = 6 a >> 2 = 3 7 is odd: true Before swap: x=5, y=3 After swap: x=3, y=5
8. instanceof Operator
public class InstanceofDemo {
public static void main(String[] args) {
Object str = "Hello";
Object num = 42;
Object list = new java.util.ArrayList<>();
System.out.println("str instanceof String: " + (str instanceof String)); // true
System.out.println("num instanceof Integer: " + (num instanceof Integer)); // true
System.out.println("str instanceof Integer: " + (str instanceof Integer)); // false
System.out.println("null instanceof String: " + (null instanceof String)); // false (always)
// Pattern matching instanceof (Java 16+)
Object value = "Hello World";
if (value instanceof String s && s.length() > 5) {
System.out.println("Long string: " + s.toUpperCase());
}
}
}str instanceof String: true num instanceof Integer: true str instanceof Integer: false null instanceof String: false Long string: HELLO WORLD
Operator Precedence (Highest to Lowest)
| Precedence | Operator | Description | ||
|---|---|---|---|---|
| 1 | () [] . | Parentheses, array access, member access | ||
| 2 | ++ -- ! ~ + - (unary) | Unary operators | ||
| 3 | * / % | Multiplicative | ||
| 4 | + - | Additive | ||
| 5 | << >> >>> | Shift | ||
| 6 | < <= > >= instanceof | Relational | ||
| 7 | == != | Equality | ||
| 8 | & | Bitwise AND | ||
| 9 | ^ | Bitwise XOR | ||
| 10 | ` | ` | Bitwise OR | |
| 11 | && | Logical AND | ||
| 12 | ` | ` | Logical OR | |
| 13 | ? : | Ternary | ||
| 14 | = += -= etc. | Assignment |
public class PrecedenceDemo {
public static void main(String[] args) {
// Multiplication before addition
System.out.println("2 + 3 * 4 = " + (2 + 3 * 4)); // 14, not 20
System.out.println("(2 + 3) * 4 = " + ((2 + 3) * 4)); // 20
// Relational before logical
int x = 5;
boolean result = x > 3 && x < 10; // (x > 3) && (x < 10)
System.out.println("5 > 3 && 5 < 10: " + result); // true
// When in doubt, use parentheses!
int a = 2, b = 3, c = 4;
int unclear = a + b * c / a - b;
int clear = a + ((b * c) / a) - b; // same result, but readable
System.out.println("Result: " + unclear + " = " + clear);
}
}2 + 3 * 4 = 14 (2 + 3) * 4 = 20 5 > 3 && 5 < 10: true Result: 5 = 5
Common Mistakes
- Using
==to compare Strings —==compares references, not content. Use.equals()for String comparison. - Integer division truncation —
5/2is2, not2.5. At least one operand must be a float/double for decimal result. - Confusing
&with&&—&is bitwise AND (evaluates both sides always),&&is logical AND (short-circuits). For boolean logic, use&&. - Increment in complex expressions —
a = a++ + ++ahas undefined behavior in some languages. In Java it's defined but confusing. Keep increments separate. - Forgetting operator precedence —
!a && bmeans(!a) && b, not!(a && b). Use parentheses when uncertain. - Right shift sign —
>>preserves the sign bit (arithmetic shift),>>>fills with 0 (logical shift). For negative numbers, they produce different results.
Interview Questions
Q1: What is the difference between == and .equals() in Java?
Answer: == compares references (memory addresses) for objects and values for primitives. .equals() compares the content/state of objects. For example, two different String objects with the same text: == returns false (different objects), .equals() returns true (same content).
Q2: What is short-circuit evaluation?
Answer: Short-circuit operators (&& and ||) skip evaluating the second operand when the result is already determined. For &&, if the first operand is false, the result is false regardless (second not evaluated). For ||, if the first is true, result is true. This is important for null checks: str != null && str.length() > 0 — if str is null, the second part is never executed, preventing NullPointerException.
Q3: What is the difference between >> and >>> in Java?
Answer: >> is the signed/arithmetic right shift — it preserves the sign bit (fills with 0 for positive, 1 for negative numbers). >>> is the unsigned/logical right shift — it always fills with 0 regardless of the sign. For positive numbers they're identical; for negative numbers, >>> produces a large positive number while >> keeps it negative.
Q4: Why does byte b = 127; b += 1; compile but byte b = 127; b = b + 1; doesn't?
Answer: Compound assignment operators (+=, -=, etc.) include an implicit cast to the left-hand side type. So b += 1 is equivalent to b = (byte)(b + 1). Without the compound operator, b + 1 promotes to int, and assigning an int to a byte requires an explicit cast: b = (byte)(b + 1).
Q5: How can you swap two numbers without a temporary variable?
Answer: Using XOR: a ^= b; b ^= a; a ^= b; or using arithmetic: a = a + b; b = a - b; a = a - b;. The XOR approach is preferred because it doesn't risk overflow. However, in practice, using a temp variable is clearer and just as efficient (compiler optimizes it).
Summary
Java provides a comprehensive set of operators covering arithmetic, comparison, logic, bit manipulation, and assignment. Key points: use &&/|| for logical operations (short-circuit), .equals() for object comparison, be aware of integer division truncation, and use parentheses to clarify precedence. Understanding operators is fundamental to writing correct and efficient Java expressions.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Operators in Java.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, syntax, basics
Related Java Master Course Topics