Operators in Java, Bitwise/Shift Operators, Precedence & Associativity
1. Topic Introduction
Operators tell the JVM what computation or decision to perform on variables. In KTU exams, operators frequently appear in two forms: (1) explaining specialized Java operators like unsigned right shift (>>>) and short-circuit logical (&&, ||) vs bitwise (&, |), and (2) tracing tricky mixed expressions using operator precedence and associativity.
Just as math evaluates multiplication before addition (5 + 2 * 3 = 11, not 21), Java follows a strict pecking order (Precedence) and tie-breaking direction (Associativity). Think of && (Short-circuit AND) like a locked two-door security room: if the first door fails (false), the guard doesn't even walk to check the second door—saving time and avoiding crashes like dividing by zero!
++, * / %, + -, << >> >>>, < >, == !=, &, ^, |, &&, ||, ?:, =) -> Associativity breaks ties (Left-to-Right for binary math, Right-to-Left for unary and assignment =).3. Essential Exam Definitions
* before +).6 / 2 * 3 evaluates (6 / 2) * 3 = 9 Left-to-Right; a = b = 5 evaluates a = (b = 5) Right-to-Left).>>>)0 (unlike signed >>, which preserves the sign bit).4. Detailed Technical Explanation & Syntax
All 6 Syllabus Operator Categories (+ Shift & instanceof)
Java organizes operators cleanly into distinct functional groups:
- 1. Arithmetic & Unary:
+,-,*,/,%(modulus works on both integers and floating-point in Java!), unary+,-, pre/post++,--. - 2. Bitwise & Shift (integer types
byte, short, int, long, charonly):&(AND),|(OR),^(XOR),~(1's complement:~n = -(n+1)),<<(left shift: multiply by2^k),>>(signed/arithmetic right shift: preserves sign bit),>>>(unsigned/zero-fill right shift: fills leading bits with0). - 3. Relational:
==,!=,>,>=,<,<=— always evaluate toboolean(true/false). Plusinstanceofto check object class compatibility at runtime. - 4. Boolean Logical & Short-Circuit:
&,|,^,!(always evaluate BOTH sides);&&and||(Short-circuit: skip right-hand operand if left-hand already determines the result!). - 5. Assignment & Compound:
=,+=,-=,*=,/=,%=(note: compound assignmentb += 5automatically performs implicit narrowing cast!). - 6. Conditional / Ternary (
?:): Compact inlineif-elseexpression:condition ? exprIfTrue : exprIfFalse.
Precedence & Associativity Table (Highest -> Lowest)
Keep this exact hierarchy handy for expression-tracing questions:
- 1. Postfix (
expr++,expr--), Member/Call (.,(),[]) — Left to Right - 2. Unary (
++expr,--expr,+,-,~,!,(type)cast) — Right to Left - 3. Multiplicative (
*,/,%) — Left to Right - 4. Additive (
+,-, String+concatenation) — Left to Right - 5. Shift (
<<,>>,>>>) — Left to Right - 6. Relational (
<,<=,>,>=,instanceof) — Left to Right - 7. Equality (
==,!=) — Left to Right - 8. Bitwise AND (
&) -> Bitwise XOR (^) -> Bitwise OR (|) — Left to Right - 9. Logical AND (
&&) -> Logical OR (||) — Left to Right - 10. Ternary (
?:) — Right to Left - 11. Assignment (
=,+=,-=, etc.) — Right to Left
5. Working Principle: Golden Rule for Tracing Complex Java Expressions
- Step 1: Evaluate operands of binary operators strictly Left-to-Right (so
x++updatesximmediately for the next operand in the same expression!). - Step 2: Apply unary prefix/postfix values at each variable's exact position.
- Step 3: Reduce operators in strict Precedence order (e.g.,
* / %before+ -, which run before>>, which runs before|).
7. Complete Java Code Examples & Tracing
>> vs >>> shifts.| 1 | public class OperatorPrecedenceDemo { |
| 2 | public static void main(String[] args) { |
| 3 | // 1. Complex Precedence & Post/Pre Increment Trace |
| 4 | int x = 2; |
| 5 | int result = x++ + x++ * --x / x++ - --x + 3 >> 1 | 2; |
| 6 | System.out.println("Traced complex result: " + result); |
| 7 | |
| 8 | // 2. Signed (>>) vs Unsigned (>>>) Right Shift on Negative Int |
| 9 | int neg = -8; |
| 10 | System.out.println("-8 >> 1 (preserves sign): " + (neg >> 1)); |
| 11 | System.out.println("-8 >>> 1 (zero-fill MSB): " + (neg >>> 1)); |
| 12 | |
| 13 | // 3. Short-Circuit && safety vs Ternary ?: |
| 14 | int denom = 0; |
| 15 | if (denom != 0 && (10 / denom) > 1) { |
| 16 | System.out.println("Safe check passed"); |
| 17 | } else { |
| 18 | System.out.println("Short-circuit prevented / by zero!"); |
| 19 | } |
| 20 | |
| 21 | int a = 15, b = 22; |
| 22 | int max = (a > b) ? a : b; |
| 23 | System.out.println("Ternary max: " + max); |
| 24 | } |
| 25 | } |
Traced complex result: 2 -8 >> 1 (preserves sign): -4 -8 >>> 1 (zero-fill MSB): 2147483644 Short-circuit prevented / by zero! Ternary max: 22
instanceof>>>>>&&||?:- Confusing bitwise
&/|(which evaluates BOTH operands) with short-circuit&&/||. - Thinking
>>and>>>behave identically on negative integers. - Applying bitwise operators (
&,~,<<) tofloatordouble(compile error!).
Comparison Tables
& vs Short-Circuit && (and | vs ||)| Feature | Boolean Logical (&, |) | Short-Circuit (&&, ||) |
|---|---|---|
| Operand Evaluation | Always evaluates both left and right sides | Skips right side if left side decides outcome |
| Allowed Types | boolean AND integer types (bitwise) | boolean ONLY |
| Null / Zero Guard | Unsafe (obj != null & obj.len > 0 crashes!) | Safe (obj != null && obj.len > 0 skips right) |
>>) vs Unsigned Right Shift (>>>)| Feature | >> (Signed Right Shift) | >>> (Unsigned Right Shift) |
|---|---|---|
| MSB Fill Bit | Copies original sign bit (0 for +ve, 1 for -ve) | Always inserts 0 regardless of sign |
| Negative Result | Remains negative (e.g., -8 >> 1 = -4) | Becomes large positive integer (-8 >>> 1 = 2147483644) |
Real-World Applications
- Bitwise flags and shifts optimize permissions, compression, and network checksums.
- Short-circuit
&&is used daily for defensive null checks:if (user != null && user.isActive()).
Important KTU Exam Points
- Explain
>>>vs>>with a negative integer example (-8). - Trace pre/post increments strictly Left-to-Right BEFORE applying operator precedence.
- Highlight String
+concatenation trap:"Sum: " + 5 + 3prints"Sum: 53", whereas"Sum: " + (5 + 3)prints"Sum: 8"!
Memory Techniques & Revision
- Bitwise Complement Shortcut:
~n = -(n + 1)(flip sign, subtract 1). - Precedence Order:
Postfix > Unary > Mul/Div > Add/Sub > Shift > Relational > Equality > Bitwise > Logical > Ternary > Assign.
Common Pitfalls to Avoid
- Forgetting that
~xequals-(x + 1)in two's complement (e.g.~11 = -12). - Writing
a + bafter a string literal without parentheses ("Ans=" + 10 + 20->Ans=1020).
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
>>(Signed Right Shift): Shifts bits right and fills vacated leftmost positions with the original sign bit (0for positive,1for negative). Example:-8 >> 1yields-4.>>>(Unsigned / Zero-Fill Right Shift): Shifts bits right and always fills vacated leftmost bits with0, turning negative numbers into large positive numbers (e.g.,-8 >>> 1yields2147483644).
Quick Understanding Check
1. What does System.out.println("Total: " + 10 + 20); output?
2. What is the value of ~11 in Java?