Operators
All Java operators: arithmetic, logical, bitwise, assignment, ternary
- Master all categories of Java operators
- Understand operator precedence and associativity
- Apply bitwise operators for low-level operations
Part of the Concept and Coding Java lecture series. These notes are fully self-contained — no prior lecture viewing is required. This chapter covers all nine categories of Java operators in depth, with special focus on bitwise operators, bitwise shift operators, operator precedence, and associativity.
Table of Contents
- Core Terminology — Operator, Operand, Expression
- Categories of Operators in Java
- Arithmetic Operators
- Relational (Comparison) Operators
- Logical Operators
- Unary Operators
- Assignment Operators
- Bitwise Operators
- Bitwise Shift Operators
- Ternary Operator
- Type Comparison Operator —
instanceof - Operator Precedence & Associativity
- Solving Complex Expressions Step by Step
- Mermaid Diagrams
- Quick-Reference Tables
- Common Mistakes
- Best Practices
- Interview Notes
- Practice Questions
- Summary Cheat Sheet
1. Core Terminology Operator, Operand, Expression
Operator
An operator is a symbol that indicates what action to perform on one or more values.
Examples:
+→ addition-→ subtraction*→ multiplication>→ greater-than comparison
Operand
An operand is the value or variable on which the operator acts.
Operands can be:
- Constants (literals):
5 + 3— both5and3are constant operands - Variables:
a + b— bothaandbare variable operands
1int a = 3, b = 4;2int result = a + b;3// ↑ ↑ ← operands4// ↑ ← operatorExpression
An expression consists of one or more operands and zero or more operators that together evaluate to a single value.
15 + 3 * 4 - a // an expression with operands (5, 3, 4, a) and operators (+, *, -)2true // a single operand, zero operators — still an expression2. Categories of Operators in Java
Java has nine categories of operators:
3. Arithmetic Operators
Definition
Arithmetic operators perform basic mathematical operations on numeric operands.
Operators
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 5 + 3 | 8 |
- | Subtraction | 5 - 3 | 2 |
* | Multiplication | 5 * 3 | 15 |
/ | Division | 5 / 2 | 2 (integer division) |
% | Modulus (remainder) | 5 % 2 | 1 |
/ performs integer division — the fractional part is discarded (not rounded).
``java
int result = 5 / 2; // result = 2, NOT 2.5
double d = 5.0 / 2; // d = 2.5 — at least one operand must be double
``Code Example
1public class ArithmeticDemo {2 public static void main(String[] args) {3 int a = 5, b = 2;4
5 System.out.println("a + b = " + (a + b)); // 76 System.out.println("a - b = " + (a - b)); // 37 System.out.println("a * b = " + (a * b)); // 108 System.out.println("a / b = " + (a / b)); // 2 (integer division)9 System.out.println("a % b = " + (a % b)); // 1 (remainder)10 }11}a + b = 7 a - b = 3 a * b = 10 a / b = 2 a % b = 1
4. Relational (Comparison) Operators
Definition
Relational operators compare two operands and always return a boolean result (trueorfalse).
Operators
| Operator | Meaning | Example (a=4, b=7) | Result |
|---|---|---|---|
== | Equal to | a == b | false |
!= | Not equal to | a != b | true |
> | Greater than | a > b | false |
< | Less than | a < b | true |
>= | Greater than or equal | a >= b | false |
<= | Less than or equal | a <= b | true |
= (assignment) with == (comparison):
``java
if (a = 5) { } // ❌ COMPILE ERROR in Java (assigns 5 to a, not a comparison)
if (a == 5) { } // ✅ correct comparison
``Code Example
1public class RelationalDemo {2 public static void main(String[] args) {3 int a = 4, b = 7;4
5 System.out.println("a == b : " + (a == b)); // false6 System.out.println("a != b : " + (a != b)); // true7 System.out.println("a > b : " + (a > b)); // false8 System.out.println("a < b : " + (a < b)); // true9 System.out.println("a >= b : " + (a >= b)); // false10 System.out.println("a <= b : " + (a <= b)); // true11 }12}a == b : false a != b : true a > b : false a < b : true a >= b : false a <= b : true
5. Logical Operators
Definition
Logical operators combine two or more boolean conditions and return a singletrueorfalse.
Operators
| Operator | Symbol | Meaning | ||
|---|---|---|---|---|
| Logical AND | && | true only if both conditions are true | ||
| Logical OR | `\ | \ | ` | true if at least one condition is true |
| Logical NOT | ! | Inverts the boolean value |
Truth Tables
AND (`&&`)
| Condition 1 | Condition 2 | Result |
|---|---|---|
false | false | false |
false | true | false |
true | false | false |
true | true | ✅ true |
OR (`||`)
| Condition 1 | Condition 2 | Result |
|---|---|---|
false | false | false |
false | true | ✅ true |
true | false | ✅ true |
true | true | ✅ true |
Short-Circuit Evaluation
This is one of the most important behaviors of logical operators.
Short-Circuit AND (`&&`)
If the first condition isfalse, Java immediately returnsfalsewithout evaluating the second condition.
Why? Because if any condition in an AND chain is false, the whole result is false — no need to check further.
1int a = 4, b = 7;2
3// Condition 1: a < 3 → false4// Since first is false, Condition 2 is NEVER evaluated5boolean result = (a < 3) && (a != b);6System.out.println(result); // falseShort-Circuit OR (`||`)
If the first condition istrue, Java immediately returnstruewithout evaluating the second condition.
Why? Because if any condition in an OR chain is true, the whole result is true.
1// Condition 1: a > 3 → true2// Since first is true, Condition 2 is NEVER evaluated3boolean result = (a > 3) || (a != b);4System.out.println(result); // truejava
// Safe null check — if obj is null, obj.method() is never called
if (obj != null && obj.method()) { }
``Code Example
1public class LogicalDemo {2 public static void main(String[] args) {3 int a = 4, b = 7;4
5 // AND examples6 System.out.println((a < 3) && (a != b)); // false && true → false7 System.out.println((a > 3) && (a != b)); // true && true → true8
9 // OR examples10 System.out.println((a < 3) || (a != b)); // false || true → true11 System.out.println((a > 3) || (a != b)); // true || true → true (short-circuit)12
13 // NOT example14 boolean flag = true;15 System.out.println(!flag); // false16 }17}false true true true false
6. Unary Operators
Definition
Unary operators
work on a single operand only.
The Five Unary Operators
| Operator | Name | Example | Effect |
|---|---|---|---|
++ | Increment | a++ or ++a | Increases value by 1 |
-- | Decrement | a-- or --a | Decreases value by 1 |
+ | Unary Plus | +a | Makes value positive (no real effect on positives) |
- | Unary Minus | -a | Negates the value |
! | Logical NOT | !flag | Flips true↔false |
Increment & Decrement Prefix vs Postfix
This is a very common interview topic and source of confusion.
Postfix (`a++`, `a--`)
Return first, then change the value.
1Step 1: Return current value of a2Step 2: Then increment (or decrement) aPrefix (`++a`, `--a`)
Change the value first, then return.
1Step 1: Increment (or decrement) a2Step 2: Then return the new valueCode Example Step by Step
1public class UnaryDemo {2 public static void main(String[] args) {3 int a = 5;4
5 // POSTFIX increment: return 5, then a becomes 66 System.out.println(a++); // prints 5 (a is now 6)7
8 // PREFIX increment: a becomes 7, then return 79 System.out.println(++a); // prints 7 (a is now 7)10
11 // POSTFIX decrement: return 7, then a becomes 612 System.out.println(a--); // prints 7 (a is now 6)13
14 // PREFIX decrement: a becomes 5, then return 515 System.out.println(--a); // prints 5 (a is now 5)16
17 // Unary minus18 System.out.println(-a); // prints -5 (a stays 5)19
20 // Logical NOT21 boolean flag = true;22 System.out.println(!flag); // prints false23 System.out.println(!flag); // prints false (flag unchanged)24 }25}5 7 7 5 -5 false false
Memory Trace
| Statement | Before | Action | Printed | After |
|---|---|---|---|---|
a++ | a=5 | Return 5, then a=6 | 5 | a=6 |
++a | a=6 | a=7, then return 7 | 7 | a=7 |
a-- | a=7 | Return 7, then a=6 | 7 | a=6 |
--a | a=6 | a=5, then return 5 | 5 | a=5 |
7. Assignment Operators
Definition
Assignment operators assign a value to a variable. The left side is always a variable; the right side is a value or expression.
Operators
| Operator | Expanded Form | Example | Equivalent |
|---|---|---|---|
= | — | a = 5 | assign 5 to a |
+= | a = a + x | a += 4 | a = a + 4 |
-= | a = a - x | a -= 3 | a = a - 3 |
*= | a = a * x | a *= 5 | a = a * 5 |
/= | a = a / x | a /= 5 | a = a / 5 |
%= | a = a % x | a %= 3 | a = a % 3 |
Code Example Full Trace
1public class AssignmentDemo {2 public static void main(String[] args) {3 int a = 5;4 int variable = 0;5
6 variable = a; // variable = 57 System.out.println(variable); // 58
9 variable += a; // variable = 5 + 5 = 1010 System.out.println(variable); // 1011
12 variable -= 3; // variable = 10 - 3 = 713 System.out.println(variable); // 714
15 variable *= a; // variable = 7 * 5 = 3516 System.out.println(variable); // 3517
18 variable /= a; // variable = 35 / 5 = 719 System.out.println(variable); // 720
21 variable %= 3; // variable = 7 % 3 = 122 System.out.println(variable); // 123 }24}5 10 7 35 7 1
Chained Assignment (Right-to-Left Associativity)
Assignment operators evaluate right to left:
1int a, b, c;2a = b = c = 10;3// Step 1: c = 104// Step 2: b = c (= 10)5// Step 3: a = b (= 10)6System.out.println(a + " " + b + " " + c); // 10 10 108. Bitwise Operators
Why Bitwise Operators?
Bitwise operators work directly on the binary bit patterns of integers. Processors handle single bit operations as single machine instructions — making bitwise operations extremely fast. They are heavily used in:
- Low-level programming (networking, embedded systems)
- Performance-critical algorithms
- DSA problems (checking even/odd, swapping, flags)
- Cryptography and encoding
The Four Bitwise Operators
| Operator | Symbol | Operation | |
|---|---|---|---|
| Bitwise AND | & | Both bits must be 1 → result is 1 | |
| Bitwise OR | `\ | ` | Either bit is 1 → result is 1 |
| Bitwise XOR | ^ | Bits are different → result is 1 | |
| Bitwise NOT | ~ | Flips all bits |
Bit-by-Bit Truth Tables
AND (`&`)
| Bit A | Bit B | A & B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 0 |
| 1 | 0 | 0 |
| 1 | 1 | 1 |
OR (`|`)
| Bit A | Bit B | A \ | B |
|---|---|---|---|
| 0 | 0 | 0 | |
| 0 | 1 | 1 | |
| 1 | 0 | 1 | |
| 1 | 1 | 1 |
XOR (`^`)
| Bit A | Bit B | A ^ B |
|---|---|---|
| 0 | 0 | 0 |
| 0 | 1 | 1 |
| 1 | 0 | 1 |
| 1 | 1 | 0 |
NOT (`~`)
| Bit | ~Bit |
|---|---|
| 0 | 1 |
| 1 | 0 |
Worked Example AND, OR, XOR
1a = 4 → binary: 0 1 0 02b = 6 → binary: 0 1 1 0AND: `a & b`
1 0 1 0 0 (4)2& 0 1 1 0 (6)3-----------4 0 1 0 0 = 4OR: `a | b`
1 0 1 0 0 (4)2| 0 1 1 0 (6)3-----------4 0 1 1 0 = 6XOR: `a ^ b`
1 0 1 0 0 (4)2^ 0 1 1 0 (6)3-----------4 0 0 1 0 = 2Code Example
1public class BitwiseDemo {2 public static void main(String[] args) {3 int a = 4; // 01004 int b = 6; // 01105
6 System.out.println("a & b = " + (a & b)); // 4 (0100)7 System.out.println("a | b = " + (a | b)); // 6 (0110)8 System.out.println("a ^ b = " + (a ^ b)); // 2 (0010)9 System.out.println("~a = " + (~a)); // -510 }11}a & b = 4 a | b = 6 a ^ b = 2 ~a = -5
8.1 Bitwise NOT (`~`) In-Depth Explanation
The ~ operator is the most confusing bitwise operator in Java because it interacts with Java's signed integer representation (two's complement).
Why `~4` gives `-5` and not `3`
Step 1: Represent +4 in 8-bit binary
1+4 = 0000 01002 ↑3 MSB = 0 → positive numberStep 2: Apply NOT (flip every bit)
1~(0000 0100)2= 1111 10113 ↑4 MSB = 1 → this is a NEGATIVE number in JavaStep 3: Find the decimal value of 1111 1011
In Java, integers are signed (no unsigned int). When MSB = 1, the number is negative.
To find the decimal value of a negative two's complement number:
11111 10112= -128 + 64 + 32 + 16 + 8 + 0 + 2 + 13= -128 + 1234= -5OR use the formula:
~n = -(n + 1)
1~4 = -(4 + 1) = -5 ✅2~0 = -(0 + 1) = -13~(-1) = -(-1 + 1) = 0Verifying with Two's Complement
We can verify that 1111 1011 is indeed -5 by computing the two's complement of 5:
1+5 = 0000 01012
3Step 1: One's complement (flip bits)4 = 1111 10105
6Step 2: Add 17 = 1111 1011 ← this IS -5 ✅~4 gives 1111 1011, and two's complement confirms that 1111 1011 = -5. ✅
Key Takeaway
In Java,~nalways equals-(n + 1)because Java integers are always signed (two's complement). There is no unsignedintin Java.
9. Bitwise Shift Operators
Overview
Shift operators move all bits of a number left or right by a specified number of positions. They are essentially very fast multiplication or division by powers of 2.
Three Types
| Operator | Symbol | Name | Effect |
|---|---|---|---|
| Left shift | << | Signed left shift | Shift bits left; fill right with 0 |
| Right shift | >> | Signed right shift | Shift bits right; fill left with sign bit |
| Unsigned right shift | >>> | Unsigned right shift | Shift bits right; fill left with 0 always |
<< → arrows point LEFT → bits move left
- >> → arrows point RIGHT → bits move right9.1 Left Shift (`<<`)
How It Works
- Shift all bits to the left by
npositions. - The leftmost bits are discarded.
- The rightmost vacated positions are always filled with
0.
Effect: Multiply by 2^n
1a << n ≡ a × 2^nWorked Example
1a = 4 → binary: 0000 01002
3a << 1 : shift left by 14 0000 1000 = 8 (4 × 2 = 8)5
6a << 2 : shift left by 27 0001 0000 = 16 (4 × 4 = 16)Visual representation:
1Original: 0 0 0 0 0 1 0 0 (4)2After <<1: 0 0 0 0 1 0 0 0 (8) ← new 0 inserted at right3After <<2: 0 0 0 1 0 0 0 0 (16) ← two 0s inserted at rightWhy There Is No Unsigned Left Shift
The least significant bit (LSB) — the rightmost bit — does not determine sign. Only the most significant bit (MSB) determines sign. Since left shift always fills the LSB positions with 0, there is no ambiguity about sign behavior. Unsigned vs signed distinction is only meaningful for the MSB (which matters when filling on the right during a right shift). Therefore, Java has no <<< operator.
9.2 Signed Right Shift (`>>`)
How It Works
- Shift all bits to the right by
npositions. - The rightmost bits are discarded.
- The leftmost vacated positions are filled with the sign bit (MSB):
- Positive number (MSB = 0) → fill with
0 - Negative number (MSB = 1) → fill with
1
Effect: Divide by 2^n (rounding toward negative infinity)
1a >> n ≡ a / 2^n (for positive numbers)Worked Example Positive Number
1a = 4 → 0000 01002
3a >> 1: shift right by 14 0000 0010 = 2 (4 / 2 = 2)5 ↑ filled with 0 (because original MSB was 0)Worked Example Negative Number
1a = -5 → 1111 1011 (two's complement of 5)2
3a >> 1: shift right by 14 1111 1101 = -3 5 ↑ filled with 1 (because original MSB was 1 — sign is preserved)Visual:
1-5: 1 1 1 1 1 0 1 12>>1: 1 1 1 1 1 1 0 1 ← 1 inserted at left (sign preserved)3 ↑ rightmost bit discarded4Result = -39.3 Unsigned Right Shift (`>>>`)
How It Works
- Shift all bits to the right by
npositions. - The rightmost bits are discarded.
- The leftmost vacated positions are always filled with
0, regardless of the sign bit.
Difference from `>>`
>> | >>> | |
|---|---|---|
| Fill bit | Sign bit (0 or 1) | Always 0 |
| Preserves sign? | ✅ Yes | ❌ No |
| Use case | Arithmetic division | Treating bits as unsigned |
Worked Example
1a = -5 → 1111 10112
3a >>> 1: shift right by 14 0111 1101 = 1255 ↑ always filled with 0 — sign NOT preservedCompared to signed:
1-5 >> 1 = -3 (sign preserved, filled with 1)2-5 >>> 1 = 125 (no sign, filled with 0)Code Example All Three Shift Operators
1public class ShiftDemo {2 public static void main(String[] args) {3 int a = 4;4
5 // Left shift6 System.out.println("4 << 1 = " + (a << 1)); // 8 (4 × 2)7 System.out.println("4 << 2 = " + (a << 2)); // 16 (4 × 4)8
9 // Signed right shift10 System.out.println("4 >> 1 = " + (a >> 1)); // 2 (4 / 2)11
12 int neg = -5;13 System.out.println("-5 >> 1 = " + (neg >> 1)); // -3 (sign preserved)14 System.out.println("-5 >>> 1 = " + (neg >>> 1)); // 2147483645 (sign not preserved)15 }16}4 << 1 = 8 4 << 2 = 16 4 >> 1 = 2 -5 >> 1 = -3 -5 >>> 1 = 2147483645
Shift Operators and Powers of 2 Summary
| Operation | Mathematical Equivalent | Example |
|---|---|---|
a << n | a × 2^n | 4 << 3 = 32 |
a >> n | a / 2^n (floor) | 32 >> 3 = 4 |
a >>> n | a / 2^n (unsigned) | -5 >>> 1 = large positive |
n is set: (num >> n) & 1
- Set bit n: num | (1 << n)
- Clear bit n: num & ~(1 << n)
- Check even/odd: num & 1 (0 = even, 1 = odd)10. Ternary Operator
Definition
The ternary operator (? :) is a compact, single-line alternative to anif-elsestatement. It evaluates a condition and returns one of two expressions depending on whether the condition istrueorfalse.
It is called "ternary" because it works on three operands: the condition, the true-expression, and the false-expression.
Syntax
1result = condition ? expressionIfTrue : expressionIfFalse;| Part | Role |
|---|---|
condition | A boolean expression — evaluates to true or false |
? | Separates condition from the true branch |
expressionIfTrue | Returned/executed if condition is true |
: | Separates true branch from false branch (the "else") |
expressionIfFalse | Returned/executed if condition is false |
Equivalent if-else
1// if-else version2int maxValue;3if (a > b) {4 maxValue = a;5} else {6 maxValue = b;7}8
9// Ternary version — identical behavior, one line10int maxValue = (a > b) ? a : b;Code Example
1public class TernaryDemo {2 public static void main(String[] args) {3 int a = 4, b = 5;4
5 // Find maximum6 int max = (a > b) ? a : b;7 System.out.println("Max: " + max); // 58
9 // Check even or odd10 String parity = (a % 2 == 0) ? "even" : "odd";11 System.out.println("a is: " + parity); // even12
13 // Nested ternary (use sparingly — reduces readability)14 int x = 10, y = 20, z = 15;15 int largest = (x > y) ? ((x > z) ? x : z) : ((y > z) ? y : z);16 System.out.println("Largest: " + largest); // 2017 }18}Max: 5 a is: even Largest: 20
if-else for readability.11. Type Comparison Operator `instanceof`
Definition
Theinstanceofoperator checks whether an object is an instance of a specific class (or its subclass, or implements an interface). It always returns aboolean.
Syntax
1object instanceof ClassNameReturns true if object is of type ClassName (or a subtype). Returns false otherwise.
Why It's Useful
Because a parent class reference can hold objects of any child class, instanceof lets you safely check the actual runtime type before casting:
1Parent ref = new Child2(); // parent reference holds Child2 object2if (ref instanceof Child2) {3 Child2 c = (Child2) ref; // safe cast — we verified the type first4}Code Example
1class Parent { }2class ChildClass1 extends Parent { }3class ChildClass2 extends Parent { }4
5public class InstanceOfDemo {6 public static void main(String[] args) {7 Object obj = new ChildClass2();8
9 System.out.println(obj instanceof ChildClass2); // true10 System.out.println(obj instanceof ChildClass1); // false11 System.out.println(obj instanceof Parent); // true (Child IS a Parent)12
13 // With child reference14 ChildClass1 child = new ChildClass1();15 System.out.println(child instanceof Parent); // true — subtype16 System.out.println(child instanceof ChildClass1);// true17
18 // With Object (parent of all)19 Object unknownObj = new ChildClass2();20 System.out.println(unknownObj instanceof ChildClass1); // false21 System.out.println(unknownObj instanceof ChildClass2); // true22
23 // String check24 String text = "Hello";25 System.out.println(text instanceof String); // true26 }27}true false true true true false true true
instanceof: Java 16 introduced a cleaner syntax that combines the instanceof check with casting:
``java
// Old way (pre-Java 16)
if (obj instanceof ChildClass2) {
ChildClass2 c = (ChildClass2) obj;
c.someMethod();
}
// New way (Java 16+)
if (obj instanceof ChildClass2 c) {
c.someMethod(); // c is automatically cast
}
``12. Operator Precedence & Associativity
What is Precedence?
When an expression contains multiple operators, precedence determines which operator is evaluated first.
Example:
15 + 2 * 3Is this (5 + 2) 3 = 21 or 5 + (2 3) = 11?
Because * has higher precedence than +, the multiplication happens first:
15 + (2 * 3) = 5 + 6 = 11What is Associativity?
When two operators have the same precedence, associativity determines the evaluation direction (left-to-right or right-to-left).
Example:
110 * 5 / 2Both * and / have the same precedence. Their associativity is left-to-right, so:
1(10 * 5) / 2 = 50 / 2 = 25Java Operator Precedence Table
(Higher row = Higher precedence = Evaluated first)
| Priority | Category | Operators | Associativity | ||
|---|---|---|---|---|---|
| 1 (Highest) | Postfix | expr++, expr-- | Left → Right | ||
| 2 | Unary prefix | ++expr, --expr, +expr, -expr, ~, ! | Right → Left | ||
| 3 | Multiplicative | *, /, % | Left → Right | ||
| 4 | Additive | +, - | Left → Right | ||
| 5 | Shift | <<, >>, >>> | Left → Right | ||
| 6 | Relational | <, >, <=, >=, instanceof | Left → Right | ||
| 7 | Equality | ==, != | Left → Right | ||
| 8 | Bitwise AND | & | Left → Right | ||
| 9 | Bitwise XOR | ^ | Left → Right | ||
| 10 | Bitwise OR | `\ | ` | Left → Right | |
| 11 | Logical AND | && | Left → Right | ||
| 12 | Logical OR | `\ | \ | ` | Left → Right |
| 13 | Ternary | ? : | Right → Left | ||
| 14 (Lowest) | Assignment | =, +=, -=, *=, /=, %=, etc. | Right → Left |
java
int result = (5 + 2) 3; // clearly 21
int result = 5 + (2 3); // clearly 11
``Worked Precedence Example
1int result = 5 + 2 * 3 - 8 / 4;Step-by-step (apply highest precedence first):
1Step 1: 2 * 3 = 6 (multiplicative)2Step 2: 8 / 4 = 2 (multiplicative)3Step 3: 5 + 6 = 11 (additive, left-to-right)4Step 4: 11 - 2 = 9 (additive)5Result: 9Worked Associativity Example
1// Assignment — right to left2int a, b, c;3a = b = c = 10;4// Step 1 (rightmost first): c = 105// Step 2: b = c (b = 10)6// Step 3: a = b (a = 10)1// Same-precedence multiplicative — left to right2int x = 10 * 5 / 2;3// Step 1 (left first): 10 * 5 = 504// Step 2: 50 / 2 = 2513. Solving Complex Expressions Step by Step
The Strategy
When you encounter a complex expression with ++, --, and multiple operators, follow this process:
- Identify and substitute all operand current values (handle postfix: return value first, then update; handle prefix: update first, then return value).
- Build the simplified numeric expression.
- Apply operator precedence (multiplication before addition, etc.).
- Compute the final result.
Worked Example from the Lecture
1int a = 4;2int result = a++ + ++a * --a + a--;Step 1: Substitute Operand Values
Track a's value as you go left to right:
| Token | Current a | Action | Value Used | a after |
|---|---|---|---|---|
a++ | 4 | Postfix: use 4, then a++ | 4 | 5 |
++a | 5 | Prefix: a++ first → 6, then use 6 | 6 | 6 |
--a | 6 | Prefix: a-- first → 5, then use 5 | 5 | 5 |
a-- | 5 | Postfix: use 5, then a-- | 5 | 4 |
Substituted expression:
14 + 6 * 5 + 5After the statement completes, a = 4.
Step 2: Apply Precedence
* has higher precedence than +:
14 + (6 * 5) + 52= 4 + 30 + 53= 39Result: 39, and a = 4 after the statement.
Practice Expression (from the lecture)
1int x = 2;2int z = ++x + x++ / x++ - 1;Trace
| Token | Current x | Action | Value Used | x after |
|---|---|---|---|---|
++x | 2 | Prefix: x=3, use 3 | 3 | 3 |
x++ | 3 | Postfix: use 3, then x=4 | 3 | 4 |
x++ | 4 | Postfix: use 4, then x=5 | 4 | 5 |
Substituted:
13 + 3 / 4 - 1Apply precedence (/ before + and -):
13 + (3 / 4) - 12= 3 + 0 - 1 ← integer division: 3/4 = 03= 2z = 2, x = 5 after the statement.
14. Mermaid Diagrams
Logical Operator Short-Circuit Flow
Prefix vs Postfix Execution Flow
Bitwise NOT Why ~4 = -5
Bit Shift Visual
15. Quick-Reference Tables
All Nine Operator Categories
| Category | Operators | Returns | Example | ||
|---|---|---|---|---|---|
| Arithmetic | + - * / % | Numeric | 5 % 2 = 1 | ||
| Relational | == != > < >= <= | boolean | 4 < 7 = true | ||
| Logical | `&& \ | \ | !` | boolean | true && false = false |
| Unary | ++ -- + - ! | Numeric / boolean | ++a, !flag | ||
| Assignment | = += -= *= /= %= | Assigns value | a += 3 | ||
| Bitwise | `& \ | ^ ~` | Numeric (bit level) | 4 & 6 = 4 | |
| Shift | << >> >>> | Numeric | 4 << 1 = 8 | ||
| Ternary | ? : | Value of chosen branch | a>b ? a : b | ||
| Type comparison | instanceof | boolean | obj instanceof String |
Bitwise Operator Truth Table (Combined)
| A | B | A & B | A \ | B | A ^ B |
|---|---|---|---|---|---|
| 0 | 0 | 0 | 0 | 0 | |
| 0 | 1 | 0 | 1 | 1 | |
| 1 | 0 | 0 | 1 | 1 | |
| 1 | 1 | 1 | 1 | 0 |
Shift Operators Fill Bit Rules
| Operator | Direction | Fill Bit | Sign Preserved? |
|---|---|---|---|
<< | Left | 0 (always) | N/A (affects MSB) |
>> | Right | Sign bit (0 or 1) | ✅ Yes |
>>> | Right | 0 (always) | ❌ No |
Prefix vs Postfix
Postfix (a++) | Prefix (++a) | |
|---|---|---|
| Step 1 | Return current value | Increment/decrement |
| Step 2 | Increment/decrement | Return new value |
| Value used in expression | Old value | New value |
16. Common Mistakes
Mistake 1: `=` vs `==`
1if (a = 5) { } // ❌ COMPILE ERROR — assignment, not comparison2if (a == 5) { } // ✅ comparisonMistake 2: Integer Division Surprise
1int result = 5 / 2;2System.out.println(result); // ❌ prints 2, NOT 2.5Fix: Use double:
1double result = 5.0 / 2; // ✅ 2.52double result = (double) 5 / 2; // ✅ also 2.5Mistake 3: Confusing Postfix and Prefix in Expressions
1int a = 5;2int b = a++; // b = 5 (old value), a = 63int c = ++a; // a = 7 first, then c = 7Many beginners assume a++ increments before the assignment. It does not — the assignment gets the old value.
Mistake 4: Expecting `~n` to Give the Bitwise Complement as Positive
1int a = 4;2System.out.println(~a); // prints -5, NOT 3Java uses signed two's complement — ~n always gives -(n+1), not just a bit flip to a positive number.
Mistake 5: Using `>>` instead of `>>>` for Unsigned Shift
1int n = -5;2System.out.println(n >> 1); // -3 (sign preserved — may not be intended)3System.out.println(n >>> 1); // 2147483645 (treats bits as unsigned)If you want to treat bits as unsigned, always use >>>.
Mistake 6: Precedence Assumption Without Parentheses
1boolean result = 4 + 3 > 5 && 2 * 3 == 6;2// Actual evaluation:3// (4+3) > 5 → 7 > 5 → true4// (2*3) == 6 → 6 == 6 → true5// true && true → trueWhile this happens to be correct, always use parentheses to make intent explicit.
Mistake 7: `instanceof` on `null`
1Object obj = null;2System.out.println(obj instanceof String); // false — does NOT throw NullPointerExceptioninstanceof safely returns false for null — it never throws NullPointerException. This can be used as a safe null check.
17. Best Practices
- Use parentheses generously to make operator precedence explicit. Code is read more than it is written — don't make readers memorize precedence tables.
- Avoid complex chained
++/--expressions in a single line. Split them across multiple statements for clarity.
- Use shift operators for power-of-2 arithmetic in performance-critical code:
x * 2→x << 1x / 4→x >> 2- But prefer readable
x * 2in normal code unless performance is critical.
- Use
>>>instead of>>when working with raw bit patterns (e.g., hashing, encoding) to avoid sign-extension surprises.
- Use
instanceofbefore casting to preventClassCastException:
1 if (obj instanceof Dog) {2 Dog dog = (Dog) obj; // safe3 }- Prefer
&&and||over&and|for boolean conditions — the short-circuit versions are safer and often more efficient.
- Use ternary for simple assignments only. Nested ternaries are hard to read — use
if-elseinstead.
- Use
BigDecimalwhen precision matters for arithmetic — never rely onfloat/doublefor exact results.
18. Interview Notes
Frequently Asked Questions
Q1: What is the difference between & and &&?
A: & is a bitwise AND — it operates on individual bits of integers. && is a logical AND for booleans with short-circuit evaluation — if the first condition is false, the second is never evaluated. When used with booleans, & still works but does NOT short-circuit.
Q2: What is the difference between >> and >>>?
A: >> is signed right shift — the vacated MSB positions are filled with the original sign bit (preserving the sign). >>> is unsigned right shift — vacated positions are always filled with 0, regardless of sign.
Q3: What is the output of ~4 in Java?
A: -5. Because ~n = -(n+1) in Java's signed two's complement representation. 4 in binary is 00000100; flipping all bits gives 11111011, which in two's complement equals -5.
Q4: What is the difference between prefix (++a) and postfix (a++) increment?
A: Postfix returns the current value and then increments. Prefix increments first and then returns the new value. Both increment the variable by 1, but the value returned to the expression differs.
Q5: What does the left shift operator << do mathematically?
A: a << n is equivalent to a × 2^n. Each left shift by 1 doubles the value. The vacated right bits are always filled with 0.
Q6: Why is there no <<< (unsigned left shift) operator in Java?
A: Because left shift only affects the right (least significant) bits, which are always filled with 0. The sign bit (MSB) is on the left — unsigned vs signed distinction only matters when filling from the left, which happens in right shifts. Since left shift always fills with 0 on the right, a separate unsigned version is unnecessary.
Q7: What is short-circuit evaluation in logical operators?
A: In &&, if the first operand is false, Java skips evaluating the second operand and immediately returns false. In ||, if the first operand is true, Java skips the second and returns true. This is used to prevent side effects and runtime errors (e.g., null pointer checks).
Q8: What does instanceof return for null?
A: It returns false — it never throws a NullPointerException. null instanceof AnyClass is always false.
Q9: What is operator precedence and associativity?
A: Precedence determines which operator is evaluated first when multiple operators appear in one expression (e.g., * before +). Associativity determines the evaluation direction when two operators have the same precedence (most Java operators are left-to-right; assignment is right-to-left).
Q10: What is the value of z and x after: int x = 2; int z = ++x + x++ / x++ - 1;?
A:
++x→ x=3, use 3x++→ use 3, then x=4x++→ use 4, then x=5- Expression:
3 + 3/4 - 1→3 + 0 - 1 = 2(integer division) - z = 2, x = 5
19. Practice Questions
Easy
- What is the output of
5 / 2and5.0 / 2in Java? - What is the difference between
==and=? - What does
a++return whena = 7? What isaafter the statement? - What does
~0evaluate to in Java? - What is
8 >> 2? What is8 << 2?
Medium
- Trace through this expression and find the output:
1 int a = 5;2 System.out.println(a++ + ++a - a--);3 // What is printed? What is a afterward?- What is the output? Explain using short-circuit evaluation:
1 int x = 0;2 boolean result = (x != 0) && (10 / x > 1);3 System.out.println(result);- Compute
13 & 10,13 | 10, and13 ^ 10by hand using binary. Verify with Java code.
- What is the result of
-8 >> 1and-8 >>> 1? Explain the difference.
- What is the output?
1 Object obj = null;2 System.out.println(obj instanceof String);Hard
- Prove that
a ^ b ^ b == afor any integeraandbusing the XOR truth table. What is this property called, and what is it used for in algorithms?
- Write a Java method using only bitwise operators (no
%or/) to check if a number is even or odd.
- Trace the full execution of:
1 int a = 4;2 int result = a++ + ++a * --a + a--;3 System.out.println(result);4 System.out.println(a);- Explain why
(int)(2.9 + 0.1)gives3but(int)(1.0 / 3.0 * 3.0)may not give1. Which operator-related concept does this illustrate?
- Use only the
<<,>>,&, and|operators to write a method that extracts then-th bit of an integer, and another that sets then-th bit.
20. Summary Cheat Sheet
1┌─────────────────────────────────────────────────────────────────────────────┐2│ JAVA OPERATORS — QUICK SUMMARY │3├─────────────────────────────────────────────────────────────────────────────┤4│ CATEGORIES (9 total) │5│ Arithmetic: + - * / % Relational: == != > < >= <= │6│ Logical: && || ! Unary: ++ -- + - ! │7│ Assignment: = += -= *= /= %= Bitwise: & | ^ ~ │8│ Shift: << >> >>> Ternary: cond ? a : b │9│ Type comparison: instanceof │10├─────────────────────────────────────────────────────────────────────────────┤11│ POSTFIX vs PREFIX │12│ a++ → use THEN increment ++a → increment THEN use │13│ a-- → use THEN decrement --a → decrement THEN use │14├─────────────────────────────────────────────────────────────────────────────┤15│ BITWISE OPERATORS │16│ & AND: both 1 → 1 | OR: any 1 → 1 │17│ ^ XOR: different → 1 ~ NOT: flip all bits │18│ ~n = -(n+1) always (Java is signed, no unsigned int) │19├─────────────────────────────────────────────────────────────────────────────┤20│ SHIFT OPERATORS │21│ a << n = a × 2^n (fill right with 0) │22│ a >> n = a ÷ 2^n (fill left with SIGN BIT — preserves sign) │23│ a >>> n = a ÷ 2^n (fill left with 0 ALWAYS — no sign preservation) │24│ No <<< exists — left shift always fills LSB with 0 (no sign issue) │25├─────────────────────────────────────────────────────────────────────────────┤26│ SHORT-CIRCUIT EVALUATION │27│ && : first false → skip rest, return false │28│ || : first true → skip rest, return true │29├─────────────────────────────────────────────────────────────────────────────┤30│ PRECEDENCE (high → low, simplified) │31│ Postfix (a++) > Prefix (++a) > Multiplicative (* / %) > │32│ Additive (+ -) > Shift (<<>>>>>>) > Relational (><>= <=) > │33│ Equality (== !=) > Bitwise & > ^ > | > && > || > ?: > Assignment (=) │34│ Associativity: most = left-to-right; assignment & ternary = right-to-left │35├─────────────────────────────────────────────────────────────────────────────┤36│ SOLVING COMPLEX EXPRESSIONS │37│ 1. Substitute operand values (handle ++ / -- order) │38│ 2. Build the numeric expression │39│ 3. Apply precedence (multiply before add, etc.) │40│ 4. Compute final result │41└─────────────────────────────────────────────────────────────────────────────┘End of Chapter — Java Operators
Next Topics: Control Flow (if-else, switch) · Loops (for, while, do-while) · Arrays · Strings
Mastery check
How well can you recall this?
Finished this lesson?