Programming in Java
Unit 3: Operators
From arithmetic to bitwise โ master every Java operator, understand precedence traps, and build real-world calculators used by fintech companies.
โฑ๏ธ Time to Complete: 4 hrs theory + 3 hrs lab | ๐ฐ Earning Potential: โน5Kโโน15K/month | ๐ 30 MCQs (Bloom's Mapped)
๐ผ Jobs this unlocks: Java Developer (โน4โ8 LPA) | Fintech Engineer (โน6โ12 LPA) | Android Developer (โน5โ10 LPA)
Opening Hook โ Operators Power India's Biggest Trading Platform
๐ข How Zerodha's P&L Calculator Uses Every Operator You'll Learn Today
Open the Zerodha Kite app and check your Profit & Loss (P&L) statement. Behind that simple green/red number is a symphony of Java operators working in real-time. Arithmetic operators calculate (sellPrice - buyPrice) * quantity. Relational operators check if (profit > 0) to show green vs red. Logical operators determine if (isIntraday && isPositionOpen) for margin calculations. Bitwise operators encode trade flags for high-speed order matching. Ternary operators decide status = (pnl >= 0) ? "PROFIT" : "LOSS".
Zerodha processes over 15 million orders per day โ each one evaluated through dozens of operator-based calculations in microseconds. Their matching engine, built in Java, uses operator precedence rules exactly like you'll learn in this chapter. One wrong bracket, one confused ++i vs i++, and millions of rupees could go wrong.
What if YOU built this? What if you understood operators so well that you could build a P&L calculator, a tax engine, or a trading bot? That's exactly what this unit teaches you โ operator by operator, trap by trap.
Learning Outcomes โ Bloom's Taxonomy Mapped (12 Outcomes)
| Bloom's Level | Learning Outcome |
|---|---|
| ๐ต Remember | LO-1: List all categories of Java operators โ arithmetic, relational, logical, bitwise, assignment, unary, and ternary |
| ๐ต Remember | LO-2: State the complete operator precedence table from highest to lowest priority |
| ๐ข Understand | LO-3: Explain the difference between pre-increment (++i) and post-increment (i++) with memory-level reasoning |
| ๐ข Understand | LO-4: Describe how short-circuit evaluation works in && and || and why it matters for null-safe code |
| ๐ก Apply | LO-5: Write Java programs using all operator types to solve real calculation problems |
| ๐ก Apply | LO-6: Use the ternary operator and instanceof to write concise conditional logic |
| ๐ Analyze | LO-7: Trace complex expressions involving mixed operators and predict exact output (interview-level) |
| ๐ Analyze | LO-8: Analyze bitwise operations to understand how flags, masks, and permissions work in system code |
| ๐ด Evaluate | LO-9: Evaluate when to use bitwise vs logical operators and justify trade-offs in performance-critical code |
| ๐ด Evaluate | LO-10: Judge common operator-related bugs (= vs ==, precedence errors) and propose fixes |
| ๐ฃ Create | LO-11: Build a complete Zerodha-style P&L calculator using all operator types |
| ๐ฃ Create | LO-12: Design a permission system using bitwise operators, similar to Unix file permissions |
Concept Explanation โ Java Operators from Scratch
Operators are the verbs of programming. Variables are nouns (data), but operators are what do things to that data โ add, compare, combine, shift, assign. Java has the richest operator set of any mainstream language. Master them, and you can express any computation in clean, efficient code.
* and / are ambulances (high priority) โ they go first no matter what. + and - are regular cars โ they wait their turn. Parentheses () are VIP escorts โ they override everything. Just like ignoring traffic rules causes accidents, ignoring precedence causes bugs.
1. Arithmetic Operators
These are your basic math operators. Simple, but full of traps โ especially integer division and modulus.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 10 + 3 | 13 |
- | Subtraction | 10 - 3 | 7 |
* | Multiplication | 10 * 3 | 30 |
/ | Division | 10 / 3 | 3 (integer division!) |
% | Modulus (Remainder) | 10 % 3 | 1 |
Java public class ArithmeticDemo { public static void main(String[] args) { int buyPrice = 1500; // Bought Infosys shares at โน1500 int sellPrice = 1750; // Sold at โน1750 int qty = 10; int profit = (sellPrice - buyPrice) * qty; System.out.println("Total Profit: โน" + profit); // โน2500 // โ ๏ธ Integer division trap! System.out.println(10 / 3); // 3, NOT 3.33! System.out.println(10.0 / 3); // 3.3333... (one operand is double) // Modulus โ check if year is leap year int year = 2024; if (year % 4 == 0) System.out.println(year + " is a leap year"); } }
7 / 2 gives 3, not 4. To get the decimal result, make at least one operand a double: 7.0 / 2 or (double) 7 / 2. This is the #1 arithmetic bug in Java interviews.
2. Relational (Comparison) Operators
Relational operators compare two values and return true or false. They're the foundation of every if statement, every loop condition, and every filter.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== | Equal to | 5 == 5 | true |
!= | Not equal to | 5 != 3 | true |
< | Less than | 3 < 5 | true |
> | Greater than | 5 > 3 | true |
<= | Less than or equal | 5 <= 5 | true |
>= | Greater than or equal | 3 >= 5 | false |
Java // Zerodha-style: Is the trade profitable? double buyPrice = 2450.75; double sellPrice = 2510.30; System.out.println(sellPrice > buyPrice); // true โ profitable! System.out.println(sellPrice == buyPrice); // false System.out.println(sellPrice != buyPrice); // true System.out.println(sellPrice >= 2500.0); // true โ above target
= is assignment, == is comparison! Writing if (x = 5) instead of if (x == 5) won't even compile in Java (unlike C/C++ where it's a silent bug). Java protects you here, but understand the difference โ interviewers love this question.
3. Logical Operators
Logical operators combine multiple boolean conditions. They're the glue that connects simple comparisons into complex business logic.
| Operator | Name | Meaning | Example |
|---|---|---|---|
&& | Logical AND | Both must be true | (age > 18) && (hasID == true) |
|| | Logical OR | At least one must be true | (isStudent) || (isSenior) |
! | Logical NOT | Flips trueโfalse | !isBlocked |
Java // Zerodha margin check: Can the user place this order? double balance = 50000; double orderValue = 45000; boolean isVerified = true; boolean isBanned = false; // AND: Both conditions must be true if (balance >= orderValue && isVerified) { System.out.println("โ Order placed!"); } // OR: At least one discount applies boolean isStudent = true; boolean isMilitary = false; if (isStudent || isMilitary) { System.out.println("๐ Discount applied!"); } // NOT: Flip the condition if (!isBanned) { System.out.println("User is active"); }
4. Bitwise Operators
Bitwise operators work on individual bits (0s and 1s) of integers. They're used in system programming, cryptography, game development, and permission systems. If you've ever wondered how Unix file permissions (chmod 755) work โ it's bitwise operators.
| Operator | Name | Description | Example (5 & 3) |
|---|---|---|---|
& | Bitwise AND | 1 only if both bits are 1 | 0101 & 0011 = 0001 โ 1 |
| | Bitwise OR | 1 if either bit is 1 | 0101 | 0011 = 0111 โ 7 |
^ | Bitwise XOR | 1 if bits are different | 0101 ^ 0011 = 0110 โ 6 |
~ | Bitwise NOT | Flips all bits | ~0101 = ...1010 โ -6 |
<< | Left Shift | Shifts bits left (multiply by 2) | 5 << 1 = 1010 โ 10 |
>> | Right Shift (Signed) | Shifts bits right (divide by 2) | 20 >> 2 = 0101 โ 5 |
>>> | Right Shift (Unsigned) | Shifts right, fills with 0 | -1 >>> 28 โ 15 |
Java public class BitwiseDemo { public static void main(String[] args) { int a = 5; // Binary: 0101 int b = 3; // Binary: 0011 System.out.println("a & b = " + (a & b)); // 1 (0001) System.out.println("a | b = " + (a | b)); // 7 (0111) System.out.println("a ^ b = " + (a ^ b)); // 6 (0110) System.out.println("~a = " + (~a)); // -6 (two's complement) System.out.println("a << 1 = " + (a << 1)); // 10 (1010) System.out.println("a >> 1 = " + (a >> 1)); // 2 (0010) // ๐ Permission system (like Unix chmod) int READ = 4; // 100 int WRITE = 2; // 010 int EXECUTE = 1; // 001 int userPerm = READ | WRITE; // 110 = 6 (read + write) System.out.println("Has READ? " + ((userPerm & READ) != 0)); // true System.out.println("Has EXEC? " + ((userPerm & EXECUTE) != 0)); // false } }
a = a ^ b; b = a ^ b; a = a ^ b; โ This swaps a and b without using a third variable. It's a classic interview question at companies like Amazon, Google, and Flipkart.
5. Assignment Operators
Assignment operators combine an arithmetic/bitwise operation with assignment โ shorthand that makes code cleaner and less error-prone.
| Operator | Equivalent | Example | Result (if x=10) |
|---|---|---|---|
= | Assign | x = 10 | x = 10 |
+= | x = x + n | x += 5 | x = 15 |
-= | x = x - n | x -= 3 | x = 7 |
*= | x = x * n | x *= 2 | x = 20 |
/= | x = x / n | x /= 4 | x = 2 |
%= | x = x % n | x %= 3 | x = 1 |
&= | x = x & n | x &= 6 | x = 2 |
|= | x = x | n | x |= 5 | x = 15 |
^= | x = x ^ n | x ^= 3 | x = 9 |
Java // Running total โ like adding items to a Flipkart cart double cartTotal = 0; cartTotal += 499.00; // Added a book cartTotal += 1299.00; // Added earphones cartTotal += 799.00; // Added a T-shirt cartTotal *= 0.9; // 10% festival discount System.out.println("Cart Total: โน" + cartTotal); // โน2337.3
byte b = 10; b += 5; works perfectly. But byte b = 10; b = b + 5; gives a compile error because b + 5 is promoted to int. This is a favourite interview trap question.
6. Unary Operators (++, -- Pre/Post)
Unary operators work on a single operand. The increment/decrement operators are the most confusing (and most tested) operators in Java.
| Operator | Name | Description |
|---|---|---|
++x | Pre-increment | Increment FIRST, then use the value |
x++ | Post-increment | Use the value FIRST, then increment |
--x | Pre-decrement | Decrement FIRST, then use the value |
x-- | Post-decrement | Use the value FIRST, then decrement |
+ | Unary plus | Indicates positive (rarely used) |
- | Unary minus | Negates the value |
! | Logical NOT | Flips boolean |
~ | Bitwise complement | Flips all bits |
๐ง The ++i vs i++ Trap โ Master This for Interviews
Golden Rule:
โข ++i (Pre): "Increment, THEN give me the value" โ Think: "Plus plus FIRST"
โข i++ (Post): "Give me the value, THEN increment" โ Think: "Use it, THEN plus plus"
Java public class UnaryTricks { public static void main(String[] args) { // === BASIC DIFFERENCE === int a = 5; int b = 5; System.out.println("a++ = " + (a++)); // Prints 5, THEN a becomes 6 System.out.println("a = " + a); // Now a is 6 System.out.println("++b = " + (++b)); // b becomes 6 FIRST, prints 6 // === TRICKY EXAMPLE 1 === int x = 10; int y = x++ + ++x; // Step 1: x++ โ use 10, x becomes 11 // Step 2: ++x โ x becomes 12, use 12 // y = 10 + 12 = 22 System.out.println("y = " + y); // 22 System.out.println("x = " + x); // 12 // === TRICKY EXAMPLE 2 === int m = 5; m = m++; // Post-increment: temp = 5, m becomes 6, then m = temp = 5 System.out.println("m = " + m); // 5! (NOT 6) // === TRICKY EXAMPLE 3 === int p = 3; int q = p++ * 2 + ++p; // Step 1: p++ โ use 3, p becomes 4 // Step 2: ++p โ p becomes 5, use 5 // q = 3 * 2 + 5 = 11 System.out.println("q = " + q); // 11 } }
m = m++ does NOT increment m! This is the most famous Java trap. Post-increment saves the old value, increments, then the assignment overwrites the incremented value with the old one. Result: m stays the same. TCS, Infosys, and Wipro love this question.
7. Ternary Operator (?:) and instanceof
Ternary Operator โ One-line if-else
Syntax: result = (condition) ? valueIfTrue : valueIfFalse;
Java // Zerodha P&L display double pnl = -2500.50; String status = (pnl >= 0) ? "โ PROFIT" : "๐ด LOSS"; System.out.println(status); // ๐ด LOSS // Nested ternary โ grade calculator int marks = 78; String grade = (marks >= 90) ? "A+" : (marks >= 75) ? "A" : (marks >= 60) ? "B" : (marks >= 40) ? "C" : "FAIL"; System.out.println("Grade: " + grade); // Grade: A
instanceof Operator โ Type Checking
Checks if an object is an instance of a particular class or interface. Essential for polymorphism and safe casting.
Java String name = "Zerodha"; System.out.println(name instanceof String); // true System.out.println(name instanceof Object); // true (String extends Object) // Safe casting pattern Object obj = "Hello Java"; if (obj instanceof String) { String s = (String) obj; System.out.println(s.toUpperCase()); // HELLO JAVA }
8. Operator Precedence Table (Complete)
When multiple operators appear in one expression, Java follows this precedence (highest first). Memorise the top 5 levels โ they appear in every exam and interview.
| Priority | Operator(s) | Description | Associativity |
|---|---|---|---|
| 1 (Highest) | () [] . :: | Parentheses, array access, member access | Left โ Right |
| 2 | ++ -- + - ~ ! (type) | Unary, cast | Right โ Left |
| 3 | * / % | Multiplicative | Left โ Right |
| 4 | + - | Additive | Left โ Right |
| 5 | << >> >>> | Shift | Left โ Right |
| 6 | < > <= >= instanceof | Relational | 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 | Right โ Left |
Java // Precedence in action โ predict the output! int result = 2 + 3 * 4; // * has higher priority than + // = 2 + (3 * 4) = 2 + 12 = 14 (NOT 20!) System.out.println(result); // 14 int r2 = 2 + 3 * 4 - 6 / 2; // = 2 + (3*4) - (6/2) = 2 + 12 - 3 = 11 System.out.println(r2); // 11 boolean check = 5 > 3 && 2 < 4 || 1 == 0; // Step 1: (5 > 3)=true, (2 < 4)=true, (1 == 0)=false // Step 2: true && true = true // Step 3: true || false = true System.out.println(check); // true
9. Short-Circuit Evaluation
Java's && and || are short-circuit operators. They stop evaluating as soon as the result is determined:
โข &&: If the first operand is false, the second is never evaluated (result is already false).
โข ||: If the first operand is true, the second is never evaluated (result is already true).
Java public class ShortCircuitDemo { public static void main(String[] args) { // === SHORT-CIRCUIT && === int x = 5; // Second condition NEVER runs because first is false if (x > 10 && ++x > 5) { System.out.println("Inside if"); } System.out.println("x = " + x); // 5 (NOT 6! โ ++x was skipped) // === SHORT-CIRCUIT || === int y = 5; // Second condition NEVER runs because first is true if (y < 10 || ++y > 5) { System.out.println("Inside if"); } System.out.println("y = " + y); // 5 (NOT 6! โ ++y was skipped) // === PRACTICAL USE: Null-safe check === String name = null; // Without short-circuit: name.length() would throw NullPointerException! // With short-circuit: if name is null, .length() is never called if (name != null && name.length() > 0) { System.out.println("Name: " + name); } else { System.out.println("Name is null or empty"); } // === NON-SHORT-CIRCUIT: & and | === int z = 5; if (z > 10 & ++z > 5) { // Single & โ BOTH sides evaluated! System.out.println("Inside if"); } System.out.println("z = " + z); // 6 (++z WAS executed) } }
if (user != null && user.getPortfolio().getValue() > 0) โ if user is null, the second part is skipped, preventing a NullPointerException. Without short-circuit, the app would crash for logged-out users.
Learn by Doing โ 3-Tier Lab: Zerodha P&L Calculator
๐ข Tier 1 โ GUIDED: Basic P&L Calculator
Problem Statement:
Build a Java program that takes buy price, sell price, and quantity of shares โ and calculates total P&L, percentage return, and displays profit/loss status.
Java import java.util.Scanner; public class PnLCalculator { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.print("Enter buy price (โน): "); double buyPrice = sc.nextDouble(); System.out.print("Enter sell price (โน): "); double sellPrice = sc.nextDouble(); System.out.print("Enter quantity: "); int qty = sc.nextInt(); // Arithmetic operators double totalBuy = buyPrice * qty; double totalSell = sellPrice * qty; double pnl = totalSell - totalBuy; double pnlPercent = (pnl / totalBuy) * 100; // Brokerage (Zerodha charges โน20 or 0.03%, whichever is lower) double brokerage = Math.min(20, totalBuy * 0.0003); double netPnl = pnl - (brokerage * 2); // Buy + Sell side // Ternary operator for status String status = (netPnl >= 0) ? "โ PROFIT" : "๐ด LOSS"; // Relational: Check if target hit boolean targetHit = pnlPercent >= 5.0; System.out.println("\nโโโ TRADE SUMMARY โโโ"); System.out.println("Buy Value: โน" + totalBuy); System.out.println("Sell Value: โน" + totalSell); System.out.println("Gross P&L: โน" + pnl); System.out.println("Brokerage: โน" + (brokerage * 2)); System.out.println("Net P&L: โน" + netPnl); System.out.printf("Return: %.2f%%\n", pnlPercent); System.out.println("Status: " + status); System.out.println("5% Target: " + (targetHit ? "HIT โ " : "NOT YET โ")); sc.close(); } }
๐ก Tier 2 โ SEMI-GUIDED: Multi-Trade Portfolio Analyzer
Your Mission:
Extend Tier 1 to handle multiple trades. Calculate overall portfolio P&L, best/worst trade, and apply tax logic.
Hints:
- Use a
whileloop to input multiple trades - Use
&&for logical checks:if (holdingDays <= 365 && pnl > 0)โ 15% STCG tax - Use
||for exit:if (choice.equals("N") || choice.equals("n")) - Use
Math.max()and relational operators to find best trade - Use compound assignment:
totalPnl += tradePnl - Use ternary for tax type:
String taxType = (days > 365) ? "LTCG (10%)" : "STCG (15%)"
int INTRADAY = 1, DELIVERY = 2, F_AND_O = 4 and check user permissions with & before allowing each trade type.
๐ด Tier 3 โ OPEN CHALLENGE: Full Zerodha Clone Console App
The Brief:
Build a complete console-based trading simulator with:
- User authentication using
&&and== - Buy/Sell operations with all arithmetic operators
- Permission system using bitwise operators (ADMIN=8, TRADE=4, VIEW=2, BASIC=1)
- P&L calculation with compound assignment operators
- Tax calculation using ternary (STCG vs LTCG)
- Risk check using logical operators:
if (pnl < -5000 && !isAdmin)โ block trading - Menu-driven with
switchand operator-based validation
Problem Set โ Syntax/Tracing + Programming + Industry + Interview
Part 1: Syntax & Tracing Questions (5 Questions)
๐ Q1: Trace the output
int a = 5, b = 10; int c = a++ + ++b - --a + b--; System.out.println("c = " + c + ", a = " + a + ", b = " + b);
Answer: Step 1: a++ โ use 5, a=6. Step 2: ++b โ b=11, use 11. Step 3: --a โ a=5, use 5. Step 4: b-- โ use 11, b=10. c = 5 + 11 - 5 + 11 = 22. Output: c = 22, a = 5, b = 10
๐ Q2: What does this print? (The m = m++ trap)
int m = 10; m = m++; m = m++; m = m++; System.out.println(m);
Answer: 10. Each m = m++ assigns the original value back. The increment is lost every time.
๐ Q3: Short-circuit trap
int x = 5, y = 10; boolean result = (x > 10) && (++y > 10); System.out.println("result = " + result + ", y = " + y);
Answer: result = false, y = 10. Since x > 10 is false, && short-circuits โ ++y never executes.
๐ Q4: Precedence puzzle
int val = 2 + 3 * 4 - 6 / 2 + 7 % 3; System.out.println(val);
Answer: 2 + 12 - 3 + 1 = 12. Multiplication, division, and modulus happen before addition/subtraction.
๐ Q5: Compound expression with post/pre increment
int i = 2; int j = i++ + i++ + ++i; System.out.println("j = " + j + ", i = " + i);
Answer: Step 1: i++ โ use 2, i=3. Step 2: i++ โ use 3, i=4. Step 3: ++i โ i=5, use 5. j = 2 + 3 + 5 = 10, i = 5. Output: j = 10, i = 5
Part 2: Programming Questions (8 Questions)
- Simple Calculator: Write a Java program that takes two numbers and an operator (+, -, *, /, %) as input and displays the result. Handle division by zero.
- Swap Without Temp: Swap two integers using (a) arithmetic operators and (b) XOR bitwise operator. Print before and after values.
- Leap Year Checker: Using
%,&&,||operators, determine if a given year is a leap year. Handle century years correctly. - Even/Odd using Bitwise: Check if a number is even or odd using the
&bitwise operator instead of%. - Grade Calculator: Using nested ternary operators, convert marks (0โ100) into grades: A+ (โฅ90), A (โฅ75), B (โฅ60), C (โฅ40), FAIL (<40).
- Bit Counter: Count the number of 1-bits (set bits) in an integer using
&and>>operators. - EMI Calculator: Calculate monthly EMI using the formula
EMI = P * r * (1+r)^n / ((1+r)^n - 1). UseMath.pow()and all arithmetic operators. - Income Tax Calculator: Build a complete Indian income tax calculator (New Regime 2024) using relational, logical, ternary, and arithmetic operators.
Part 3: Industry-Style Questions (3 Questions)
- Razorpay Transaction Validator: Write a program that validates a payment: amount must be > 0, โค 100000, user must be verified, and account must not be frozen. Use
&&,||,!, and ternary operators. - PhonePe Cashback Engine: Implement a cashback calculator: 5% for UPI, 2% for wallet, 10% for first-time users (use
&&), capped at โน100. UseMath.min()and ternary. - Zerodha Order Type Classifier: Given order flags using bitwise encoding (BIT_0=BUY/SELL, BIT_1=LIMIT/MARKET, BIT_2=INTRADAY/DELIVERY), decode the order type using
&and display it.
Part 4: Interview Questions (3 Questions)
- [TCS/Infosys] What is the output?
System.out.println(10 + 20 + "Hello" + 30 + 40);โ Explain the string concatenation vs addition rule. - [Amazon/Flipkart] Explain the difference between
&and&&with a code example showing when they produce different results. - [Google/Microsoft] Given an array of integers where every element appears twice except one, find the single element using XOR. Explain why
a ^ a = 0anda ^ 0 = a.
MCQ Assessment Bank โ 30 Questions (Bloom's Mapped)
Remember / Identify (Q1โQ5)
Which of the following is the modulus operator in Java?
/%//mod
% โ The modulus operator returns the remainder after division. // is a comment in Java, not an operator.The instanceof operator in Java is used to:
- Create a new object
- Check if an object is of a particular type
- Compare two objects for equality
- Cast an object to another type
instanceof checks whether an object is an instance of a specified class or interface. Returns true or false.Which operator has the highest precedence in Java?
*++()=
() โ Parentheses have the highest precedence and can override all other operator priorities.The >>> operator in Java is called:
- Signed right shift
- Unsigned right shift
- Triple right shift
- Bitwise rotate
>>> is the unsigned right shift operator. It always fills the leftmost bits with 0, regardless of the sign bit.Which of these is NOT an assignment operator in Java?
+=-==!%=
=! โ This is not a valid operator. The correct "not equal" comparison is !=. Common confusion in exams.Understand / Explain (Q6โQ10)
What is the output of System.out.println(10 / 3);?
3.33343.0
3 โ Integer division truncates the decimal part. Both operands are int, so the result is int.What does short-circuit evaluation mean in &&?
- Both operands are always evaluated
- If the first operand is false, the second is not evaluated
- The operator short-circuits the program and exits
- It evaluates from right to left
&&, if the left side is false, the entire expression is false regardless of the right side. Java skips the right side entirely.Why does byte b = 10; b = b + 5; cause a compile error but b += 5; doesn't?
- Both cause compile errors
b + 5promotes toint;+=does implicit casting+=is faster than+ =- It's a Java bug
b + 5 returns an int, which can't be assigned to byte without explicit cast. Compound operators (+=) include an implicit cast.What is the difference between ++i and i++?
- No difference โ both increment by 1
++iincrements first then returns;i++returns first then increments++iincrements by 2;i++increments by 1i++is faster than++i
++i) increments the variable and returns the new value. Post-increment (i++) returns the current value and then increments.What does ~5 evaluate to in Java?
-5-646
-6 โ Bitwise NOT flips all bits. In two's complement: ~n = -(n+1). So ~5 = -6.Apply / Use (Q11โQ15)
What is the output?int a = 5; System.out.println(a++);
564- Compile error
5 โ Post-increment: prints the current value (5) first, then increments a to 6.What is the output?int a = 5; System.out.println(++a);
564- Compile error
6 โ Pre-increment: increments a to 6 first, then prints 6.What is the output?int x = 10; int y = x++ + ++x; System.out.println(y);
21222023
22 โ x++: use 10, x=11. ++x: x=12, use 12. y = 10 + 12 = 22.What is the output?System.out.println(10 > 5 ? "YES" : "NO");
YESNOtrue- Compile error
YES โ 10 > 5 is true, so the ternary returns "YES".What is 12 & 10?
814102
8 โ 12 = 1100, 10 = 1010. AND: 1000 = 8.Analyze / Trace (Q16โQ20)
What is the output?int m = 5; m = m++; System.out.println(m);
564- Compile error
5 โ The classic trap! Post-increment returns old value (5), then m becomes 6, but assignment overwrites it back to 5.What is the output?int a = 5; boolean b = (a > 3) || (++a > 5); System.out.println(a);
564- Compile error
5 โ Short-circuit ||: a > 3 is true, so ++a is never evaluated. a remains 5.What is the output?System.out.println(10 + 20 + "Hello" + 30 + 40);
10020Hello304030Hello304030Hello70100
30Hello3040 โ Left to right: 10+20=30 (arithmetic), then "30"+"Hello"="30Hello" (concatenation), then +"30"+"40" (concatenation continues).What is the output?int x = 3, y = 5; System.out.println(x > y ? x : y);
35truefalse
5 โ 3 > 5 is false, so the ternary returns y = 5. This is a classic max-of-two pattern.What is the output?int a = 5; int b = (a > 3) && (a++ > 4) ? a : a + 10; System.out.println(b);
561516
6 โ a > 3 = true. a++ > 4 = true (uses 5, then a=6). Condition = true, returns a = 6.Evaluate / Judge (Q21โQ25)
Which code correctly checks if a number is even using bitwise operators?
if (n | 1 == 0)if ((n & 1) == 0)if (n ^ 1 == 0)if (~n == 0)
n & 1 extracts the last bit. If it's 0, the number is even. This is faster than n % 2 at the hardware level.Why should you prefer && over & for logical conditions?
&doesn't work with booleans&&short-circuits, avoiding unnecessary evaluation and potential errors&is deprecated- No difference โ they're identical
&& short-circuits: if the left is false, the right isn't evaluated. This prevents NullPointerException in patterns like obj != null && obj.method().A programmer writes if (x = 5) instead of if (x == 5). What happens in Java?
- Compiles and runs โ always true
- Compiles and runs โ always false
- Compile error (incompatible types)
- Runtime error
if requires a boolean. x = 5 returns an int, causing a compile error. Java protects you from this C/C++ pitfall.Which approach is better for multiplying by 2?
n * 2โ more readablen << 1โ faster at hardware level- Both compile to the same bytecode; prefer
n * 2for readability n + nโ avoids multiplication overhead
n * 2 to a shift instruction automatically. Use n * 2 for readability; use n << 1 only in extreme performance-critical code.What is the risk of deeply nested ternary operators?
- They cause runtime errors
- They're slower than if-else
- They reduce readability and increase maintenance complexity
- Java doesn't allow nesting ternary operators
Create / Design (Q26โQ30)
To swap two numbers without a temp variable using XOR, the correct sequence is:
a ^= b; a ^= b; b ^= a;a ^= b; b ^= a; a ^= b;b ^= a; a ^= b; b ^= a;a = a ^ b; b = a; a = b;
a ^= b (a has combined), b ^= a (b gets original a), a ^= b (a gets original b).To implement a permission system where READ=4, WRITE=2, EXECUTE=1, which expression grants read+write?
READ + WRITEREAD | WRITEREAD & WRITEREAD ^ WRITE
READ | WRITE โ Bitwise OR combines permission flags: 100 | 010 = 110 (6). While + also works here, | is the correct idiom because it's idempotent (applying a permission twice doesn't break it).What is the output?int i = 1; int j = i++ + i++ + i++; System.out.println("j=" + j + " i=" + i);
j=3 i=4j=6 i=4j=6 i=3j=3 i=3
j=6 i=4 โ Step by step: i++=1(iโ2), i++=2(iโ3), i++=3(iโ4). j = 1+2+3 = 6. i = 4.To find the maximum of three numbers using ternary operators, which expression is correct?
int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);int max = a > b > c ? a : c;int max = (a > b && a > c) ? a;int max = a ? b ? c;
What does n & (n - 1) do when n is a power of 2?
- Returns
n - Returns
0 - Returns
n - 1 - Returns
1
0 โ Powers of 2 have exactly one set bit (e.g., 8=1000). n-1 flips all bits below it (7=0111). AND gives 0000. This is used to check if a number is a power of 2: if ((n & (n-1)) == 0).Short Answer Questions (8 Questions)
SA-1: List all categories of operators in Java with one example each.
Answer:
- Arithmetic:
+, -, *, /, %โ Example:10 % 3 = 1 - Relational:
==, !=, <, >, <=, >=โ Example:5 > 3 โ true - Logical:
&&, ||, !โ Example:true && false โ false - Bitwise:
&, |, ^, ~, <<, >>, >>>โ Example:5 & 3 = 1 - Assignment:
=, +=, -=, *=, /=, %=โ Example:x += 5 - Unary:
++, --, +, -, !, ~โ Example:++a - Ternary:
?:โ Example:(a > b) ? a : b - instanceof: โ Example:
"hello" instanceof String โ true
SA-2: Explain the difference between == and = in Java.
Answer: = is the assignment operator โ it assigns a value to a variable (x = 5). == is the equality operator โ it compares two values and returns true or false (x == 5). Using = inside an if condition (e.g., if (x = 5)) causes a compile error in Java because if requires a boolean, not an int. This is a safety feature compared to C/C++ where it silently compiles.
SA-3: What is short-circuit evaluation? Give an example where it prevents an error.
Answer: Short-circuit evaluation means Java stops evaluating a logical expression as soon as the result is determined. For &&, if the left side is false, the right side is skipped. For ||, if the left side is true, the right side is skipped.
Example: if (str != null && str.length() > 0) โ If str is null, the && short-circuits and str.length() is never called, preventing a NullPointerException.
SA-4: Explain the output of m = m++ when m = 5.
Answer: Output: m = 5 (not 6). Here's why: Post-increment first saves the current value of m (5) as a temporary, then increments m to 6, then the assignment m = writes back the saved temporary value (5), overwriting the incremented value. Net result: m stays at 5. This is one of the most asked Java interview questions.
SA-5: What is the ternary operator? Write its syntax and a practical example.
Answer: The ternary operator ?: is Java's only operator that takes three operands. It's a compact if-else.
Syntax: result = (condition) ? valueIfTrue : valueIfFalse;
Example: String status = (marks >= 40) ? "PASS" : "FAIL";
This replaces a 5-line if-else block with a single line. Use it for simple conditions; avoid nesting more than 2 levels deep for readability.
SA-6: How do bitwise shift operators work? Explain << and >>.
Answer:
Left shift (<<): Shifts all bits to the left by specified positions. Each shift left multiplies the number by 2. Example: 5 << 2 = 5 ร 4 = 20. Binary: 00000101 โ 00010100.
Right shift (>>): Shifts all bits to the right. Each shift right divides the number by 2 (integer division). Example: 20 >> 2 = 20 รท 4 = 5. For negative numbers, the sign bit (1) is preserved (arithmetic shift).
Unsigned right shift (>>>): Same as >> but always fills with 0 (not the sign bit). Used when you need logical shift regardless of sign.
SA-7: What is the instanceof operator? When do you use it?
Answer: instanceof checks whether an object is an instance of a particular class, subclass, or interface. It returns true or false.
Example: "hello" instanceof String โ true.
Use cases: (1) Safe downcasting before calling subclass-specific methods. (2) Type checking in polymorphic code. (3) Handling different types in a collection of Objects. In modern Java (16+), pattern matching with instanceof allows: if (obj instanceof String s) { ... use s ... }.
SA-8: Why is operator precedence important? Give an example where wrong precedence causes a bug.
Answer: Operator precedence determines the order in which operators are evaluated in an expression. Without understanding precedence, calculations produce unexpected results.
Bug example: A student writes int total = price + tax * quantity; intending (price + tax) * quantity. But since * has higher precedence than +, Java evaluates it as price + (tax * quantity). If price=100, tax=18, quantity=5: Expected: 590, Actual: 190. Fix: Use parentheses โ (price + tax) * quantity.
Long Answer Questions (3 Questions)
LA-1: Explain all types of operators in Java with examples and a complete program demonstrating each.
Answer:
Java provides 8 categories of operators:
1. Arithmetic Operators (+, -, *, /, %): Perform mathematical operations. Key trap: integer division (7/2 = 3, not 3.5). Modulus (%) gives remainder โ essential for checking even/odd, leap years, and cyclic patterns.
2. Relational Operators (==, !=, <, >, <=, >=): Compare values and return boolean. Used in every if/while/for condition. Note: == compares values for primitives but references for objects (use .equals() for object content comparison).
3. Logical Operators (&&, ||, !): Combine boolean expressions. && requires both true; || requires at least one true; ! negates. Support short-circuit evaluation for performance and null-safety.
4. Bitwise Operators (&, |, ^, ~, <<, >>, >>>): Operate on individual bits. Used in permission systems, cryptography, compression, and hardware programming. XOR (^) enables swap without temp and finding unique elements.
5. Assignment Operators (=, +=, -=, *=, etc.): Assign values with optional computation. Compound operators include implicit type casting โ byte b = 5; b += 3; works without explicit cast.
6. Unary Operators (++, --, +, -, !, ~): Work on single operand. Pre-increment (++i) changes before use; post-increment (i++) changes after use. The m = m++ trap is a classic interview question.
7. Ternary Operator (?:): Three-operand conditional: condition ? valueIfTrue : valueIfFalse. Concise replacement for simple if-else. Can be nested but should be limited to 2 levels for readability.
8. instanceof: Type-checking operator returning boolean. Essential for safe casting in polymorphic code.
Java public class AllOperatorsDemo { public static void main(String[] args) { // 1. Arithmetic System.out.println("15 / 4 = " + (15 / 4)); // 3 System.out.println("15 % 4 = " + (15 % 4)); // 3 // 2. Relational System.out.println("5 >= 5: " + (5 >= 5)); // true // 3. Logical System.out.println("T && F: " + (true && false)); // false // 4. Bitwise System.out.println("5 ^ 3 = " + (5 ^ 3)); // 6 // 5. Assignment int x = 10; x += 5; System.out.println("x += 5: " + x); // 15 // 6. Unary int a = 5; System.out.println("a++: " + (a++)); // 5 System.out.println("++a: " + (++a)); // 7 // 7. Ternary String r = (x > 10) ? "Big" : "Small"; System.out.println("Ternary: " + r); // Big // 8. instanceof System.out.println("instanceof: " + ("Hi" instanceof String)); // true } }
LA-2: Explain operator precedence and associativity in Java with a complete precedence table and worked-out expression evaluation examples.
Answer:
Operator precedence determines which operator is evaluated first when multiple operators appear in a single expression. Operator associativity determines the direction of evaluation when operators of the same precedence appear together.
Key Rules:
- Higher precedence operators are evaluated first
- Parentheses
()override all precedence - Most operators associate left-to-right; unary, ternary, and assignment associate right-to-left
- When in doubt, use parentheses โ they cost nothing and prevent bugs
Worked Example 1: int result = 2 + 3 * 4 - 6 / 2 + 7 % 3;
Step 1 (*, /, %): 3*4=12, 6/2=3, 7%3=1
Step 2 (+, -, left to right): 2+12=14, 14-3=11, 11+1=12
Result: 12
Worked Example 2: boolean check = 5 > 3 && 2 < 4 || 1 == 0;
Step 1 (relational): 5>3=true, 2<4=true, 1==0=false
Step 2 (&&): true && true = true
Step 3 (||): true || false = true
Result: true
Worked Example 3: int v = ++a * b-- + c / --d; (a=2, b=3, c=10, d=5)
Step 1 (unary, right-to-left): ++aโa=3,use 3. b--โuse 3,b=2. --dโd=4,use 4.
Step 2 (*, /): 3*3=9, 10/4=2
Step 3 (+): 9+2=11
Result: v = 11
LA-3: Explain bitwise operators in Java with practical real-world applications. Include a program that implements a file permission system using bitwise operators.
Answer:
Bitwise operators manipulate individual bits of integer values. They are fundamental to systems programming, networking, cryptography, and optimization.
Real-world Applications:
- Permission systems: Unix
chmoduses bitwise flags (Read=4, Write=2, Execute=1) - Network programming: IP subnet masks use bitwise AND
- Cryptography: XOR is the basis of many encryption algorithms
- Game development: Entity component systems use bitmasks for component flags
- Compression: Huffman coding manipulates individual bits
Java public class PermissionSystem { // Permission flags static final int READ = 4; // 100 static final int WRITE = 2; // 010 static final int EXECUTE = 1; // 001 public static void main(String[] args) { // Grant permissions using OR int admin = READ | WRITE | EXECUTE; // 111 = 7 int user = READ | EXECUTE; // 101 = 5 int guest = READ; // 100 = 4 // Check permission using AND System.out.println("Admin can write: " + ((admin & WRITE) != 0)); // true System.out.println("Guest can write: " + ((guest & WRITE) != 0)); // false // Revoke permission using AND + NOT admin = admin & ~EXECUTE; // Remove execute: 110 = 6 System.out.println("Admin after revoke exec: " + admin); // Toggle permission using XOR user = user ^ WRITE; // Toggle write: 101โ111 = 7 System.out.println("User after toggle write: " + user); } }
Lab Programs
All lab programs for this unit are covered in Section D (Learn by Doing). The 3-tier lab structure provides guided, semi-guided, and open-ended programming exercises using all operator types. Refer to Section D for:
- ๐ข Tier 1 โ Basic P&L Calculator (Guided)
- ๐ก Tier 2 โ Multi-Trade Portfolio Analyzer (Semi-Guided)
- ๐ด Tier 3 โ Full Trading Simulator (Open Challenge)
Industry Spotlight โ A Day in the Life
๐จโ๐ป Rohan Desai, 25 โ Backend Engineer at Zerodha, Bangalore
Background: B.Tech (CS) from VJTI Mumbai. Average student โ 7.2 CGPA. Self-taught Java in 2nd year through online courses. Built a stock portfolio tracker as a college project. Got noticed during Zerodha's hiring hackathon where his operator-heavy matching engine logic impressed the panel.
A Typical Day:
9:00 AM โ Pre-market prep. Review overnight code deployments. Check that the order matching engine is operational before 9:15 AM market open.
9:15 AM โ Markets open. Monitor real-time order flow. The matching engine processes 15M+ orders daily using Java โ every order goes through operator-based validation: if (orderQty > 0 && balance >= orderValue && !isAccountFrozen).
11:00 AM โ Fix a bug in P&L calculation. A user reported wrong brokerage deduction. Root cause: operator precedence issue โ totalValue - brokerage * 2 was being evaluated as totalValue - (brokerage * 2) when it should have been (totalValue - brokerage) * 2. Added parentheses.
2:00 PM โ Implement a new permission flag for F&O (Futures & Options) trading using bitwise operators. Existing flags: EQUITY=1, COMMODITY=2, CURRENCY=4. Added FNO=8.
4:00 PM โ Write unit tests for edge cases in the tax calculation module. Test STCG vs LTCG logic using ternary operators.
5:30 PM โ Code review for a junior dev. Caught a == vs .equals() bug in string comparison and an m = m++ error in a loop counter.
| Detail | Info |
|---|---|
| Tools Used Daily | Java 17, IntelliJ IDEA, Git, Kafka, Redis, PostgreSQL, Prometheus |
| Entry Salary (2024) | โน6โ10 LPA + ESOPs |
| Mid-Level (3โ5 yrs) | โน15โ25 LPA |
| Senior (7+ yrs) | โน30โ50 LPA |
| Companies Hiring Java Devs | Zerodha, Razorpay, PhonePe, Groww, CRED, Swiggy, Flipkart, Goldman Sachs, JP Morgan, TCS, Infosys |
i++ vs ++i questions in interviews. Operators seem easy, but the tricky cases separate good programmers from great ones. Build small projects, trace code by hand, and understand what happens at every step."
Earn With It โ Freelance & Income Roadmap
๐ฐ Your Earning Path After This Chapter
Portfolio Piece: "Zerodha-style P&L Calculator" โ a polished Java console app demonstrating all operator types with clean code and error handling.
Beginner Gig Ideas:
โข Simple calculator apps (Java/Android) for local businesses โ โน2,000โโน5,000
โข EMI/Loan calculators for banking coaching institutes โ โน3,000โโน8,000
โข Tax calculator tools for CA firms โ โน5,000โโน12,000
โข Grade/CGPA calculator for colleges โ โน2,000โโน6,000
โข Unit converter apps (currency, temperature, distance) โ โน1,500โโน4,000
| Platform | Best For | Typical Rate |
|---|---|---|
| Internshala | Java projects for startups | โน3,000โโน10,000/project |
| Fiverr | Calculator/utility apps | $15โ$60/gig (โน1,200โโน5,000) |
| GitHub + Resume | Portfolio for job applications | Indirect โ lands โน4โ8 LPA jobs |
| College Projects | Help juniors with Java assignments | โน500โโน2,000/assignment |
| WhatsApp/Local | Calculator tools for local shops | โน2,000โโน8,000/project |
โฑ๏ธ Time to First Earning: 1โ2 weeks (if you complete the P&L calculator and list it on Fiverr/Internshala)
Chapter Summary & Code Tweet
๐ Key Takeaways
โ Java has 8 operator categories: Arithmetic, Relational, Logical, Bitwise, Assignment, Unary, Ternary, and instanceof
โ
Integer division truncates โ 7/2 = 3 (not 3.5). Use 7.0/2 for decimal results
โ
++i vs i++ โ Pre-increment changes THEN returns; Post-increment returns THEN changes
โ
m = m++ = m stays unchanged โ the most famous Java trap
โ
Short-circuit evaluation in && and || skips unnecessary evaluation โ essential for null-safe code
โ Bitwise operators enable permission systems, fast math, and unique algorithms (XOR swap, power-of-2 check)
โ
Operator precedence: () โ Unary โ * / % โ + - โ Relational โ Equality โ Bitwise โ Logical โ Ternary โ Assignment
โ
Compound assignment (+=) includes implicit casting โ works with byte and short
โ
= is assignment, == is comparison โ Java protects you with compile errors unlike C/C++
โ
instanceof checks object type โ essential for safe casting in polymorphic code
๐ฆ Code Tweet โ Entire Chapter in One Code Block
Java // Java Operators โ The Complete Cheat Sheet ๐ int a=10,b=3; a+b-b*b/b%b; // Arithmetic: + - * / % a==b; a!=b; a>b; a<b; // Relational: == != > < >= <= true&&false; true||false; !true; // Logical: && || ! a&b; a|b; a^b; ~a; a<<1; a>>1; // Bitwise a+=5; a-=3; a*=2; // Assignment ++a; a++; --a; a--; // Unary (pre/post) (a>b)?"Y":"N"; // Ternary "hi" instanceof String; // instanceof // ๐ m=m++ โ m stays same. ++i before, i++ after!
Self-Assessment Checkpoint
| Skill / Concept | Tool / Technique | Deliverable | Earning Ready? |
|---|---|---|---|
| Arithmetic Operators | Java โ +, -, *, /, % | P&L Calculator | โ Yes โ calculator apps |
| Relational Operators | Java โ ==, !=, <, >, <=, >= | Condition-based programs | โ Yes โ validation logic |
| Logical Operators | Java โ &&, ||, ! | Multi-condition checks | โ Yes โ business rule engines |
| Bitwise Operators | Java โ &, |, ^, ~, <<, >> | Permission system | โ Yes โ system programming |
| Unary Operators | Java โ ++i, i++, --i, i-- | Tracing exercises | โ Yes โ interview prep coaching |
| Ternary & instanceof | Java โ ?: and instanceof | Concise conditional logic | โ Yes โ cleaner code |
| Operator Precedence | Conceptual + tracing | Expression evaluation | โ Yes โ interview questions |
| Short-Circuit Evaluation | Java โ &&, || behaviour | Null-safe patterns | โ Yes โ production code |
โ Unit 3 complete. MCQs: 30. Ready for Unit 4!
[QR: Link to EduArtha video tutorial โ Java Operators Deep Dive]