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)

Section A

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.

๐Ÿ‡ฎ๐Ÿ‡ณ Zerodha๐Ÿ‡ฎ๐Ÿ‡ณ Groww๐Ÿ‡ฎ๐Ÿ‡ณ Razorpay๐Ÿ‡ฎ๐Ÿ‡ณ PhonePe๐Ÿ‡ฎ๐Ÿ‡ณ Paytm Money๐Ÿ‡ฎ๐Ÿ‡ณ CRED
Zerodha, founded by Nithin Kamath in 2010, is India's largest stockbroker with 15+ million clients. Their entire trading engine is built in Java. Every single trade passes through operator-based validation logic โ€” the same operators you're about to learn. Mastering operators isn't just academic โ€” it's the foundation of fintech worth โ‚น2 lakh crore.
Section B

Learning Outcomes โ€” Bloom's Taxonomy Mapped (12 Outcomes)

Bloom's LevelLearning Outcome
๐Ÿ”ต RememberLO-1: List all categories of Java operators โ€” arithmetic, relational, logical, bitwise, assignment, unary, and ternary
๐Ÿ”ต RememberLO-2: State the complete operator precedence table from highest to lowest priority
๐ŸŸข UnderstandLO-3: Explain the difference between pre-increment (++i) and post-increment (i++) with memory-level reasoning
๐ŸŸข UnderstandLO-4: Describe how short-circuit evaluation works in && and || and why it matters for null-safe code
๐ŸŸก ApplyLO-5: Write Java programs using all operator types to solve real calculation problems
๐ŸŸก ApplyLO-6: Use the ternary operator and instanceof to write concise conditional logic
๐ŸŸ  AnalyzeLO-7: Trace complex expressions involving mixed operators and predict exact output (interview-level)
๐ŸŸ  AnalyzeLO-8: Analyze bitwise operations to understand how flags, masks, and permissions work in system code
๐Ÿ”ด EvaluateLO-9: Evaluate when to use bitwise vs logical operators and justify trade-offs in performance-critical code
๐Ÿ”ด EvaluateLO-10: Judge common operator-related bugs (= vs ==, precedence errors) and propose fixes
๐ŸŸฃ CreateLO-11: Build a complete Zerodha-style P&L calculator using all operator types
๐ŸŸฃ CreateLO-12: Design a permission system using bitwise operators, similar to Unix file permissions
Section C

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.

Operator precedence = Delhi traffic rules. * 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.

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division10 / 33 (integer division!)
%Modulus (Remainder)10 % 31
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");
    }
}
Total Profit: โ‚น2500 3 3.3333333333333335 2024 is a leap year
Integer division drops the decimal โ€” it doesn't round! 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.

OperatorMeaningExampleResult
==Equal to5 == 5true
!=Not equal to5 != 3true
<Less than3 < 5true
>Greater than5 > 3true
<=Less than or equal5 <= 5true
>=Greater than or equal3 >= 5false
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.

OperatorNameMeaningExample
&&Logical ANDBoth must be true(age > 18) && (hasID == true)
||Logical ORAt least one must be true(isStudent) || (isSenior)
!Logical NOTFlips 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");
}
โœ… Order placed! ๐ŸŽ Discount applied! 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.

OperatorNameDescriptionExample (5 & 3)
&Bitwise AND1 only if both bits are 10101 & 0011 = 0001 โ†’ 1
|Bitwise OR1 if either bit is 10101 | 0011 = 0111 โ†’ 7
^Bitwise XOR1 if bits are different0101 ^ 0011 = 0110 โ†’ 6
~Bitwise NOTFlips all bits~0101 = ...1010 โ†’ -6
<<Left ShiftShifts 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 & b = 1 a | b = 7 a ^ b = 6 ~a = -6 a << 1 = 10 a >> 1 = 2 Has READ? true Has EXEC? false
XOR trick for swapping without a temp variable: 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.

OperatorEquivalentExampleResult (if x=10)
=Assignx = 10x = 10
+=x = x + nx += 5x = 15
-=x = x - nx -= 3x = 7
*=x = x * nx *= 2x = 20
/=x = x / nx /= 4x = 2
%=x = x % nx %= 3x = 1
&=x = x & nx &= 6x = 2
|=x = x | nx |= 5x = 15
^=x = x ^ nx ^= 3x = 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
Cart Total: โ‚น2337.3
Compound assignment operators do implicit casting! 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.

OperatorNameDescription
++xPre-incrementIncrement FIRST, then use the value
x++Post-incrementUse the value FIRST, then increment
--xPre-decrementDecrement FIRST, then use the value
x--Post-decrementUse the value FIRST, then decrement
+Unary plusIndicates positive (rarely used)
-Unary minusNegates the value
!Logical NOTFlips boolean
~Bitwise complementFlips 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
    }
}
a++ = 5 a = 6 ++b = 6 y = 22 x = 12 m = 5 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.

PriorityOperator(s)DescriptionAssociativity
1 (Highest)() [] . ::Parentheses, array access, member accessLeft โ†’ Right
2++ -- + - ~ ! (type)Unary, castRight โ†’ Left
3* / %MultiplicativeLeft โ†’ Right
4+ -AdditiveLeft โ†’ Right
5<< >> >>>ShiftLeft โ†’ Right
6< > <= >= instanceofRelationalLeft โ†’ Right
7== !=EqualityLeft โ†’ Right
8&Bitwise ANDLeft โ†’ Right
9^Bitwise XORLeft โ†’ Right
10|Bitwise ORLeft โ†’ Right
11&&Logical ANDLeft โ†’ Right
12||Logical ORLeft โ†’ Right
13?:TernaryRight โ†’ Left
14 (Lowest)= += -= *= /= %=AssignmentRight โ†’ 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
14 11 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)
    }
}
x = 5 Inside if y = 5 Name is null or empty z = 6
Short-circuit evaluation saves Zerodha from crashing. When checking a user's portfolio: 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.
Section D

Learn by Doing โ€” 3-Tier Lab: Zerodha P&L Calculator

๐ŸŸข Tier 1 โ€” GUIDED: Basic P&L Calculator

โฑ๏ธ 45โ€“60 minutesBeginnerUses: Arithmetic, Relational, Ternary

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();
    }
}
Enter buy price (โ‚น): 1500 Enter sell price (โ‚น): 1620 Enter quantity: 50 โ•โ•โ• TRADE SUMMARY โ•โ•โ• Buy Value: โ‚น75000.0 Sell Value: โ‚น81000.0 Gross P&L: โ‚น6000.0 Brokerage: โ‚น40.0 Net P&L: โ‚น5960.0 Return: 8.00% Status: โœ… PROFIT 5% Target: HIT โœ…

๐ŸŸก Tier 2 โ€” SEMI-GUIDED: Multi-Trade Portfolio Analyzer

โฑ๏ธ 60โ€“90 minutesIntermediateUses: All operators + loops

Your Mission:

Extend Tier 1 to handle multiple trades. Calculate overall portfolio P&L, best/worst trade, and apply tax logic.

Hints:

  1. Use a while loop to input multiple trades
  2. Use && for logical checks: if (holdingDays <= 365 && pnl > 0) โ†’ 15% STCG tax
  3. Use || for exit: if (choice.equals("N") || choice.equals("n"))
  4. Use Math.max() and relational operators to find best trade
  5. Use compound assignment: totalPnl += tradePnl
  6. Use ternary for tax type: String taxType = (days > 365) ? "LTCG (10%)" : "STCG (15%)"
Stretch Goal: Add a bitwise permission flag โ€” use 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

โฑ๏ธ 2โ€“3 hoursAdvancedNo instructions โ€” real-world mini-project

The Brief:

Build a complete console-based trading simulator with:

  1. User authentication using && and ==
  2. Buy/Sell operations with all arithmetic operators
  3. Permission system using bitwise operators (ADMIN=8, TRADE=4, VIEW=2, BASIC=1)
  4. P&L calculation with compound assignment operators
  5. Tax calculation using ternary (STCG vs LTCG)
  6. Risk check using logical operators: if (pnl < -5000 && !isAdmin) โ†’ block trading
  7. Menu-driven with switch and operator-based validation
This exact project structure is what fintech startups build during hackathons. Polish it, add a README, push to GitHub, and mention it in your resume. Recruiters at Zerodha, Groww, and Razorpay specifically look for fintech projects.
Section E

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)

  1. Simple Calculator: Write a Java program that takes two numbers and an operator (+, -, *, /, %) as input and displays the result. Handle division by zero.
  2. Swap Without Temp: Swap two integers using (a) arithmetic operators and (b) XOR bitwise operator. Print before and after values.
  3. Leap Year Checker: Using %, &&, || operators, determine if a given year is a leap year. Handle century years correctly.
  4. Even/Odd using Bitwise: Check if a number is even or odd using the & bitwise operator instead of %.
  5. Grade Calculator: Using nested ternary operators, convert marks (0โ€“100) into grades: A+ (โ‰ฅ90), A (โ‰ฅ75), B (โ‰ฅ60), C (โ‰ฅ40), FAIL (<40).
  6. Bit Counter: Count the number of 1-bits (set bits) in an integer using & and >> operators.
  7. EMI Calculator: Calculate monthly EMI using the formula EMI = P * r * (1+r)^n / ((1+r)^n - 1). Use Math.pow() and all arithmetic operators.
  8. 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)

  1. 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.
  2. PhonePe Cashback Engine: Implement a cashback calculator: 5% for UPI, 2% for wallet, 10% for first-time users (use &&), capped at โ‚น100. Use Math.min() and ternary.
  3. 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)

  1. [TCS/Infosys] What is the output? System.out.println(10 + 20 + "Hello" + 30 + 40); โ€” Explain the string concatenation vs addition rule.
  2. [Amazon/Flipkart] Explain the difference between & and && with a code example showing when they produce different results.
  3. [Google/Microsoft] Given an array of integers where every element appears twice except one, find the single element using XOR. Explain why a ^ a = 0 and a ^ 0 = a.
Section F

MCQ Assessment Bank โ€” 30 Questions (Bloom's Mapped)

Remember / Identify (Q1โ€“Q5)

Q1

Which of the following is the modulus operator in Java?

  1. /
  2. %
  3. //
  4. mod
Remember
โœ… Answer: (B) % โ€” The modulus operator returns the remainder after division. // is a comment in Java, not an operator.
Q2

The instanceof operator in Java is used to:

  1. Create a new object
  2. Check if an object is of a particular type
  3. Compare two objects for equality
  4. Cast an object to another type
Remember
โœ… Answer: (B) โ€” instanceof checks whether an object is an instance of a specified class or interface. Returns true or false.
Q3

Which operator has the highest precedence in Java?

  1. *
  2. ++
  3. ()
  4. =
Remember
โœ… Answer: (C) () โ€” Parentheses have the highest precedence and can override all other operator priorities.
Q4

The >>> operator in Java is called:

  1. Signed right shift
  2. Unsigned right shift
  3. Triple right shift
  4. Bitwise rotate
Remember
โœ… Answer: (B) โ€” >>> is the unsigned right shift operator. It always fills the leftmost bits with 0, regardless of the sign bit.
Q5

Which of these is NOT an assignment operator in Java?

  1. +=
  2. -=
  3. =!
  4. %=
Remember
โœ… Answer: (C) =! โ€” This is not a valid operator. The correct "not equal" comparison is !=. Common confusion in exams.

Understand / Explain (Q6โ€“Q10)

Q6

What is the output of System.out.println(10 / 3);?

  1. 3.33
  2. 3
  3. 4
  4. 3.0
Understand
โœ… Answer: (B) 3 โ€” Integer division truncates the decimal part. Both operands are int, so the result is int.
Q7

What does short-circuit evaluation mean in &&?

  1. Both operands are always evaluated
  2. If the first operand is false, the second is not evaluated
  3. The operator short-circuits the program and exits
  4. It evaluates from right to left
Understand
โœ… Answer: (B) โ€” In &&, if the left side is false, the entire expression is false regardless of the right side. Java skips the right side entirely.
Q8

Why does byte b = 10; b = b + 5; cause a compile error but b += 5; doesn't?

  1. Both cause compile errors
  2. b + 5 promotes to int; += does implicit casting
  3. += is faster than + =
  4. It's a Java bug
Understand
โœ… Answer: (B) โ€” b + 5 returns an int, which can't be assigned to byte without explicit cast. Compound operators (+=) include an implicit cast.
Q9

What is the difference between ++i and i++?

  1. No difference โ€” both increment by 1
  2. ++i increments first then returns; i++ returns first then increments
  3. ++i increments by 2; i++ increments by 1
  4. i++ is faster than ++i
Understand
โœ… Answer: (B) โ€” Pre-increment (++i) increments the variable and returns the new value. Post-increment (i++) returns the current value and then increments.
Q10

What does ~5 evaluate to in Java?

  1. -5
  2. -6
  3. 4
  4. 6
Understand
โœ… Answer: (B) -6 โ€” Bitwise NOT flips all bits. In two's complement: ~n = -(n+1). So ~5 = -6.

Apply / Use (Q11โ€“Q15)

Q11

What is the output?
int a = 5; System.out.println(a++);

  1. 5
  2. 6
  3. 4
  4. Compile error
Apply
โœ… Answer: (A) 5 โ€” Post-increment: prints the current value (5) first, then increments a to 6.
Q12

What is the output?
int a = 5; System.out.println(++a);

  1. 5
  2. 6
  3. 4
  4. Compile error
Apply
โœ… Answer: (B) 6 โ€” Pre-increment: increments a to 6 first, then prints 6.
Q13

What is the output?
int x = 10; int y = x++ + ++x; System.out.println(y);

  1. 21
  2. 22
  3. 20
  4. 23
Apply
โœ… Answer: (B) 22 โ€” x++: use 10, x=11. ++x: x=12, use 12. y = 10 + 12 = 22.
Q14

What is the output?
System.out.println(10 > 5 ? "YES" : "NO");

  1. YES
  2. NO
  3. true
  4. Compile error
Apply
โœ… Answer: (A) YES โ€” 10 > 5 is true, so the ternary returns "YES".
Q15

What is 12 & 10?

  1. 8
  2. 14
  3. 10
  4. 2
Apply
โœ… Answer: (A) 8 โ€” 12 = 1100, 10 = 1010. AND: 1000 = 8.

Analyze / Trace (Q16โ€“Q20)

Q16

What is the output?
int m = 5; m = m++; System.out.println(m);

  1. 5
  2. 6
  3. 4
  4. Compile error
Analyze
โœ… Answer: (A) 5 โ€” The classic trap! Post-increment returns old value (5), then m becomes 6, but assignment overwrites it back to 5.
Q17

What is the output?
int a = 5; boolean b = (a > 3) || (++a > 5); System.out.println(a);

  1. 5
  2. 6
  3. 4
  4. Compile error
Analyze
โœ… Answer: (A) 5 โ€” Short-circuit ||: a > 3 is true, so ++a is never evaluated. a remains 5.
Q18

What is the output?
System.out.println(10 + 20 + "Hello" + 30 + 40);

  1. 10020Hello3040
  2. 30Hello3040
  3. 30Hello70
  4. 100
Analyze
โœ… Answer: (B) 30Hello3040 โ€” Left to right: 10+20=30 (arithmetic), then "30"+"Hello"="30Hello" (concatenation), then +"30"+"40" (concatenation continues).
Q19

What is the output?
int x = 3, y = 5; System.out.println(x > y ? x : y);

  1. 3
  2. 5
  3. true
  4. false
Analyze
โœ… Answer: (B) 5 โ€” 3 > 5 is false, so the ternary returns y = 5. This is a classic max-of-two pattern.
Q20

What is the output?
int a = 5; int b = (a > 3) && (a++ > 4) ? a : a + 10; System.out.println(b);

  1. 5
  2. 6
  3. 15
  4. 16
Analyze
โœ… Answer: (B) 6 โ€” a > 3 = true. a++ > 4 = true (uses 5, then a=6). Condition = true, returns a = 6.

Evaluate / Judge (Q21โ€“Q25)

Q21

Which code correctly checks if a number is even using bitwise operators?

  1. if (n | 1 == 0)
  2. if ((n & 1) == 0)
  3. if (n ^ 1 == 0)
  4. if (~n == 0)
Evaluate
โœ… Answer: (B) โ€” n & 1 extracts the last bit. If it's 0, the number is even. This is faster than n % 2 at the hardware level.
Q22

Why should you prefer && over & for logical conditions?

  1. & doesn't work with booleans
  2. && short-circuits, avoiding unnecessary evaluation and potential errors
  3. & is deprecated
  4. No difference โ€” they're identical
Evaluate
โœ… Answer: (B) โ€” && short-circuits: if the left is false, the right isn't evaluated. This prevents NullPointerException in patterns like obj != null && obj.method().
Q23

A programmer writes if (x = 5) instead of if (x == 5). What happens in Java?

  1. Compiles and runs โ€” always true
  2. Compiles and runs โ€” always false
  3. Compile error (incompatible types)
  4. Runtime error
Evaluate
โœ… Answer: (C) โ€” In Java, if requires a boolean. x = 5 returns an int, causing a compile error. Java protects you from this C/C++ pitfall.
Q24

Which approach is better for multiplying by 2?

  1. n * 2 โ€” more readable
  2. n << 1 โ€” faster at hardware level
  3. Both compile to the same bytecode; prefer n * 2 for readability
  4. n + n โ€” avoids multiplication overhead
Evaluate
โœ… Answer: (C) โ€” Modern JVMs optimise n * 2 to a shift instruction automatically. Use n * 2 for readability; use n << 1 only in extreme performance-critical code.
Q25

What is the risk of deeply nested ternary operators?

  1. They cause runtime errors
  2. They're slower than if-else
  3. They reduce readability and increase maintenance complexity
  4. Java doesn't allow nesting ternary operators
Evaluate
โœ… Answer: (C) โ€” Deeply nested ternary operators become unreadable. Use them for simple conditions; switch to if-else for complex logic. Clean code matters in team environments.

Create / Design (Q26โ€“Q30)

Q26

To swap two numbers without a temp variable using XOR, the correct sequence is:

  1. a ^= b; a ^= b; b ^= a;
  2. a ^= b; b ^= a; a ^= b;
  3. b ^= a; a ^= b; b ^= a;
  4. a = a ^ b; b = a; a = b;
Create
โœ… Answer: (B) โ€” The correct XOR swap: a ^= b (a has combined), b ^= a (b gets original a), a ^= b (a gets original b).
Q27

To implement a permission system where READ=4, WRITE=2, EXECUTE=1, which expression grants read+write?

  1. READ + WRITE
  2. READ | WRITE
  3. READ & WRITE
  4. READ ^ WRITE
Create
โœ… Answer: (B) 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).
Q28

What is the output?
int i = 1; int j = i++ + i++ + i++; System.out.println("j=" + j + " i=" + i);

  1. j=3 i=4
  2. j=6 i=4
  3. j=6 i=3
  4. j=3 i=3
Create
โœ… Answer: (B) 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.
Q29

To find the maximum of three numbers using ternary operators, which expression is correct?

  1. int max = (a > b) ? (a > c ? a : c) : (b > c ? b : c);
  2. int max = a > b > c ? a : c;
  3. int max = (a > b && a > c) ? a;
  4. int max = a ? b ? c;
Create
โœ… Answer: (A) โ€” Nested ternary: first compare a and b, then compare the winner with c. Options B, C, D have syntax errors.
Q30

What does n & (n - 1) do when n is a power of 2?

  1. Returns n
  2. Returns 0
  3. Returns n - 1
  4. Returns 1
Create
โœ… Answer: (B) 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).
Section G

Short Answer Questions (8 Questions)

SA-1: List all categories of operators in Java with one example each.

Answer:

  1. Arithmetic: +, -, *, /, % โ€” Example: 10 % 3 = 1
  2. Relational: ==, !=, <, >, <=, >= โ€” Example: 5 > 3 โ†’ true
  3. Logical: &&, ||, ! โ€” Example: true && false โ†’ false
  4. Bitwise: &, |, ^, ~, <<, >>, >>> โ€” Example: 5 & 3 = 1
  5. Assignment: =, +=, -=, *=, /=, %= โ€” Example: x += 5
  6. Unary: ++, --, +, -, !, ~ โ€” Example: ++a
  7. Ternary: ?: โ€” Example: (a > b) ? a : b
  8. 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.

Section H

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:

  1. Higher precedence operators are evaluated first
  2. Parentheses () override all precedence
  3. Most operators associate left-to-right; unary, ternary, and assignment associate right-to-left
  4. 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:

  1. Permission systems: Unix chmod uses bitwise flags (Read=4, Write=2, Execute=1)
  2. Network programming: IP subnet masks use bitwise AND
  3. Cryptography: XOR is the basis of many encryption algorithms
  4. Game development: Entity component systems use bitmasks for component flags
  5. 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);
    }
}
Section I

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)
Complete all three tiers for maximum learning. Tier 1 teaches you the operators. Tier 2 tests if you can apply them independently. Tier 3 proves you can architect a real application โ€” which is what employers look for.
Section J

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.

DetailInfo
Tools Used DailyJava 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 DevsZerodha, Razorpay, PhonePe, Groww, CRED, Swiggy, Flipkart, Goldman Sachs, JP Morgan, TCS, Infosys
Rohan's advice to students: "Don't skip the basics. I've seen IIT graduates fail at 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."
Section K

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

PlatformBest ForTypical Rate
InternshalaJava projects for startupsโ‚น3,000โ€“โ‚น10,000/project
FiverrCalculator/utility apps$15โ€“$60/gig (โ‚น1,200โ€“โ‚น5,000)
GitHub + ResumePortfolio for job applicationsIndirect โ€” lands โ‚น4โ€“8 LPA jobs
College ProjectsHelp juniors with Java assignmentsโ‚น500โ€“โ‚น2,000/assignment
WhatsApp/LocalCalculator 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)

The calculator app market on Google Play Store is huge. Simple ad-supported calculator apps can earn โ‚น5,000โ€“โ‚น15,000/month passively once they reach 10K+ downloads. Start with a "GST Calculator for Indian Businesses" or "Indian Income Tax Calculator" โ€” high demand, low competition.
Section L

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!
Section M

Self-Assessment Checkpoint

Skill / ConceptTool / TechniqueDeliverableEarning Ready?
Arithmetic OperatorsJava โ€” +, -, *, /, %P&L Calculatorโœ… Yes โ€” calculator apps
Relational OperatorsJava โ€” ==, !=, <, >, <=, >=Condition-based programsโœ… Yes โ€” validation logic
Logical OperatorsJava โ€” &&, ||, !Multi-condition checksโœ… Yes โ€” business rule engines
Bitwise OperatorsJava โ€” &, |, ^, ~, <<, >>Permission systemโœ… Yes โ€” system programming
Unary OperatorsJava โ€” ++i, i++, --i, i--Tracing exercisesโœ… Yes โ€” interview prep coaching
Ternary & instanceofJava โ€” ?: and instanceofConcise conditional logicโœ… Yes โ€” cleaner code
Operator PrecedenceConceptual + tracingExpression evaluationโœ… Yes โ€” interview questions
Short-Circuit EvaluationJava โ€” &&, || behaviourNull-safe patternsโœ… Yes โ€” production code
Minimum Viable Earning Setup after this chapter: A GitHub repo with 3 calculator projects (P&L, EMI, Tax) + a Fiverr/Internshala profile offering "Java Calculator Development" = you can earn โ‚น5,000โ€“โ‚น15,000/month from calculator and utility app gigs while still in college.

โœ… Unit 3 complete. MCQs: 30. Ready for Unit 4!

[QR: Link to EduArtha video tutorial โ€” Java Operators Deep Dive]