Programming in Java

Unit 5: Loops, Arrays & Enums

Master iteration, data storage with arrays, and type-safe constants with enumerations — build real Indian stock analyzers and student grade processors.

⏱️ 6 hrs theory + 5 hrs lab  |  💰 ₹5K–₹20K/month  |  📝 30 MCQs (Bloom's Mapped)

💼 Jobs: Backend Developer (₹5–10 LPA)  |  Software Engineer (₹6–15 LPA)  |  Competitive Programmer (₹8–20 LPA)

Section A

Opening Hook — The Engine Behind Every Product You Browse

🛒 How Flipkart Shows You Millions of Products in Milliseconds

Open Flipkart and search "wireless earbuds." Within 200 milliseconds, the app returns thousands of products — sorted by relevance, price, rating, and availability. Behind the scenes, Java code iterates through arrays of millions of product objects using optimised loops. Each product's price, rating, stock count, and seller info is stored in arrays and traversed using for loops, filtered using if conditions inside while loops, and categorised using enum types (ELECTRONICS, FASHION, HOME, etc.).

At NSE India, the Nifty 50 index recalculates every second during trading hours. A stock price analyzer takes an array of 375 one-minute candle prices (6.25 hours × 60 minutes), loops through them to compute moving averages, find day-high/day-low, detect crossover patterns, and flag breakout signals. Every one of these operations is fundamentally a loop iterating over an array.

Zerodha's Kite platform processes 15 million+ orders daily. Their backend, largely written in Java and Go, uses enum types for order status (PENDING, EXECUTED, CANCELLED, REJECTED) and arrays for real-time tick data. Without loops and arrays, modern trading platforms simply cannot exist.

🇮🇳 Flipkart🇮🇳 NSE India🇮🇳 Zerodha🇮🇳 Amazon India🇮🇳 Infosys🇮🇳 TCS
A single Google search triggers approximately 1,000 computers working in parallel, each running loops over arrays of indexed web pages. The Java for loop is the most-used control structure in production codebases — appearing in 94% of all Java projects on GitHub (2024 analysis). Arrays remain the #1 data structure in every programming language, used more than lists, maps, and trees combined.
Section B

Learning Outcomes — Bloom's Taxonomy Mapped

Bloom's LevelLearning Outcome
🔵 RememberList the syntax of for, while, do-while loops and state rules for array declaration in Java
🔵 RememberDefine enumeration, ordinal(), values(), and name() methods with correct signatures
🔵 UnderstandExplain the difference between for, enhanced for-each, while, and do-while loops with flowchart reasoning
🔵 UnderstandDescribe how 1D and 2D arrays are stored in memory and why ArrayIndexOutOfBoundsException occurs
🟢 ApplyWrite a Java program using nested for loops to multiply two matrices and display the result
🟢 ApplyUse java.util.Arrays methods (sort, binarySearch, fill, copyOf) to process student marks data
🟢 AnalyzeCompare the performance of for vs enhanced for-each for array traversal and identify when each is optimal
🟢 AnalyzeDebug a given loop-based program containing off-by-one errors, infinite loops, and incorrect break placement
🟠 EvaluateAssess whether to use arrays, ArrayList, or enum for a given real-world scenario with justification
🟠 EvaluateCritique a Nifty stock price analysis program for correctness, efficiency, and code quality
🟠 CreateDesign and implement a complete student marks analyzer using arrays, loops, and the Arrays utility class
🟠 CreateBuild an enum-based menu-driven application with EnumSet and EnumMap for an Indian railway booking scenario
Section C

Concept Explanation — Loops, Arrays & Enums from Scratch

1. The for Loop

The for loop is the workhorse of Java programming. It's used when you know exactly how many times you want to repeat an action. Think of it as a railway ticket counter — you know there are 50 people in the queue, so you serve exactly 50.

🔄 Anatomy of a for Loop

Syntax:
Java
for (initialization; condition; update) {
    // body — executes while condition is true
}
Execution Flow:

1. Initialization executes once. 2. Condition is checked — if true, body executes. 3. Update runs after each iteration. 4. Go back to step 2.

Example — Print numbers 1 to 10:
Java
for (int i = 1; i <= 10; i++) {
    System.out.print(i + " ");
}
// Output: 1 2 3 4 5 6 7 8 9 10
Example — Sum of first N natural numbers:
Java
int n = 100, sum = 0;
for (int i = 1; i <= n; i++) {
    sum += i;
}
System.out.println("Sum = " + sum); // Sum = 5050
Off-by-one error: Using < instead of <= (or vice versa) is the most common loop bug. for(int i=0; i<10; i++) runs 10 times (0–9), while for(int i=0; i<=10; i++) runs 11 times (0–10). Always think: "Do I need the boundary value included?"

2. Enhanced for-each Loop

Introduced in Java 5, the enhanced for loop simplifies array/collection traversal. You don't manage an index variable — Java does it for you. Think of it as an automatic toll booth vs a manual one.

Java
int[] prices = {1500, 1520, 1480, 1550, 1600};

// Traditional for loop
for (int i = 0; i < prices.length; i++) {
    System.out.println(prices[i]);
}

// Enhanced for-each — cleaner, safer
for (int price : prices) {
    System.out.println(price);
}
Use for-each when you only need to READ elements. Use traditional for when you need the index (e.g., to modify elements, compare adjacent elements, or traverse backwards). For-each cannot modify the original array elements or access the index.

3. The while Loop

Use while when you don't know in advance how many iterations are needed. Think of it as waiting for a bus — you wait while the bus hasn't arrived. You don't know when it will come.

🔄 while Loop — Condition-First Iteration

Java
// Read user input until they enter -1 (sentinel value)
import java.util.Scanner;

Scanner sc = new Scanner(System.in);
int num = 0;
int count = 0;

System.out.println("Enter numbers (-1 to stop):");
num = sc.nextInt();

while (num != -1) {
    count++;
    System.out.println("You entered: " + num);
    num = sc.nextInt();
}
System.out.println("Total numbers entered: " + count);
Featurefor loopwhile loop
Best WhenCount is known in advanceCount depends on a condition
InitializationInside the for statementBefore the loop
Use CaseIterating arrays, countingReading input, waiting for events
RiskOff-by-one errorsInfinite loop if condition never becomes false

4. The do-while Loop

The do-while loop always executes at least once, because the condition is checked after the body. Think of it like an ATM — the machine shows you the menu at least once, then asks "Do you want another transaction?"

Java
// Menu-driven program using do-while
Scanner sc = new Scanner(System.in);
int choice;

do {
    System.out.println("\n=== Student Management System ===");
    System.out.println("1. Add Student");
    System.out.println("2. View Marks");
    System.out.println("3. Calculate Average");
    System.out.println("4. Exit");
    System.out.print("Enter choice: ");
    choice = sc.nextInt();

    switch (choice) {
        case 1: System.out.println("Adding student..."); break;
        case 2: System.out.println("Viewing marks..."); break;
        case 3: System.out.println("Calculating average..."); break;
        case 4: System.out.println("Goodbye!"); break;
        default: System.out.println("Invalid choice!");
    }
} while (choice != 4);

5. Loop Control: break, continue & Labeled Break

🎮 Controlling Loop Flow

break — Exit the loop immediately:
Java
// Find first stock price above ₹2000
int[] prices = {1800, 1900, 1750, 2100, 2200};
for (int i = 0; i < prices.length; i++) {
    if (prices[i] > 2000) {
        System.out.println("Found at index " + i + ": ₹" + prices[i]);
        break; // stop searching
    }
}
continue — Skip this iteration, go to next:
Java
// Print only passing marks (>= 40)
int[] marks = {85, 32, 91, 28, 76, 45};
for (int mark : marks) {
    if (mark < 40) continue; // skip failures
    System.out.println("Pass: " + mark);
}
Labeled break — Exit outer loop from inside inner loop:
Java
// Search for a value in a 2D matrix
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
int target = 5;
boolean found = false;

outer:
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        if (matrix[i][j] == target) {
            System.out.println("Found at ["+i+"]["+j+"]");
            found = true;
            break outer; // exits BOTH loops
        }
    }
}

6. One-Dimensional Arrays

An array is a fixed-size container that holds multiple values of the same type. Think of it as a row of lockers in a hostel — each locker has a number (index), and you can put one item (value) in each locker. Locker numbers start at 0, not 1.

📦 Array Declaration, Initialization & Traversal

Java
// Declaration
int[] marks;                        // preferred style
int marks2[];                       // C-style (avoid)

// Initialization — static
int[] marks = {85, 92, 78, 96, 88};

// Initialization — dynamic
int[] marks = new int[5];          // all elements default to 0
marks[0] = 85;
marks[1] = 92;

// Traversal
for (int i = 0; i < marks.length; i++) {
    System.out.println("marks[" + i + "] = " + marks[i]);
}

// Passing array to a method
public static int findMax(int[] arr) {
    int max = arr[0];
    for (int val : arr) {
        if (val > max) max = val;
    }
    return max;
}

Full Program: StudentMarksAnalyzer

Java
import java.util.Scanner;

public class StudentMarksAnalyzer {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int[] marks = new int[10];

        // Input marks
        System.out.println("Enter marks of 10 students:");
        for (int i = 0; i < 10; i++) {
            System.out.print("Student " + (i+1) + ": ");
            marks[i] = sc.nextInt();
        }

        // Calculate sum, max, min
        int sum = 0, max = marks[0], min = marks[0];
        for (int m : marks) {
            sum += m;
            if (m > max) max = m;
            if (m < min) min = m;
        }
        double avg = sum / 10.0;

        // Count above average
        int aboveAvg = 0;
        for (int m : marks) {
            if (m > avg) aboveAvg++;
        }

        // Output
        System.out.println("\n--- Results ---");
        System.out.println("Average:  " + avg);
        System.out.println("Highest:  " + max);
        System.out.println("Lowest:   " + min);
        System.out.println("Above Avg: " + aboveAvg + " students");
    }
}
Enter marks of 10 students: Student 1: 85 Student 2: 92 Student 3: 78 Student 4: 96 Student 5: 88 Student 6: 72 Student 7: 91 Student 8: 83 Student 9: 67 Student 10: 95 --- Results --- Average: 84.7 Highest: 96 Lowest: 67 Above Avg: 5 students
Array index starts at 0, not 1. An array of size 5 has valid indices 0, 1, 2, 3, 4. Accessing arr[5] throws ArrayIndexOutOfBoundsException. This is the #1 runtime error for Java beginners.

7. Two-Dimensional Arrays (Matrices)

A 2D array is an "array of arrays" — like a spreadsheet with rows and columns. Used for matrices, game boards, seating arrangements, and image pixel data.

Java
// Declaration & initialization
int[][] matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9}
};

// Traversal — row-major order
for (int i = 0; i < matrix.length; i++) {
    for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + "\t");
    }
    System.out.println();
}

Full Program: MatrixMultiplier

Java
public class MatrixMultiplier {
    public static void main(String[] args) {
        int[][] A = {
            {1, 2, 3},
            {4, 5, 6},
            {7, 8, 9}
        };
        int[][] B = {
            {9, 8, 7},
            {6, 5, 4},
            {3, 2, 1}
        };
        int rows = 3, cols = 3;
        int[][] C = new int[rows][cols];

        // Matrix multiplication: C[i][j] = sum of A[i][k] * B[k][j]
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                C[i][j] = 0;
                for (int k = 0; k < cols; k++) {
                    C[i][j] += A[i][k] * B[k][j];
                }
            }
        }

        // Print result
        System.out.println("Result of A × B:");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                System.out.printf("%6d", C[i][j]);
            }
            System.out.println();
        }
    }
}
Result of A × B: 30 18 6 84 57 30 138 96 54

8. Multi-Dimensional Arrays

Java supports arrays of any dimension. A 3D array is an "array of 2D arrays" — useful for storing data like RGB image channels (height × width × 3 colors) or a building's room layout (floor × row × room).

Java
// 3D array: 2 floors, 3 rows, 4 rooms per row
int[][][] building = new int[2][3][4];
building[0][1][2] = 101; // Floor 0, Row 1, Room 2 = Room No. 101

// Traversal
for (int f = 0; f < building.length; f++)
    for (int r = 0; r < building[f].length; r++)
        for (int rm = 0; rm < building[f][r].length; rm++)
            System.out.println("Floor "+f+" Row "+r+" Room "+rm+" = "+building[f][r][rm]);

9. Array Access & Common Operations

OperationCodeNotes
Access elementarr[i]0-indexed; O(1) time
Get lengtharr.lengthProperty, not method (no parentheses)
Modify elementarr[i] = valueO(1) time
Find elementLoop through arrayO(n) linear search
Out of boundsarr[arr.length]Throws ArrayIndexOutOfBoundsException
arr.length is a field, not a method. Don't write arr.length() — that's for Strings. Arrays use arr.length (no parentheses). Strings use str.length() (with parentheses). This trips up students every exam.

10. The java.util.Arrays Class

The Arrays utility class provides powerful static methods for common array operations. Think of it as a Swiss Army knife for arrays — sorting, searching, copying, filling, and printing all in one import.

Java
import java.util.Arrays;

public class ArraysDemo {
    public static void main(String[] args) {
        int[] data = {45, 12, 89, 33, 67, 23, 91};

        // 1. toString() — print array contents
        System.out.println("Original: " + Arrays.toString(data));
        // [45, 12, 89, 33, 67, 23, 91]

        // 2. sort() — sorts in ascending order (Dual-Pivot Quicksort)
        Arrays.sort(data);
        System.out.println("Sorted:   " + Arrays.toString(data));
        // [12, 23, 33, 45, 67, 89, 91]

        // 3. binarySearch() — find element (array MUST be sorted first)
        int idx = Arrays.binarySearch(data, 67);
        System.out.println("67 found at index: " + idx); // 4

        // 4. fill() — fill entire array with a value
        int[] zeros = new int[5];
        Arrays.fill(zeros, 42);
        System.out.println("Filled:   " + Arrays.toString(zeros));
        // [42, 42, 42, 42, 42]

        // 5. copyOf() — create a copy with specified length
        int[] copy = Arrays.copyOf(data, 5); // first 5 elements
        System.out.println("Copy(5):  " + Arrays.toString(copy));
        // [12, 23, 33, 45, 67]

        // 6. equals() — compare two arrays
        int[] a = {1,2,3}, b = {1,2,3};
        System.out.println("Equal? " + Arrays.equals(a, b)); // true

        // 7. deepToString() — for 2D arrays
        int[][] mat = {{1,2},{3,4}};
        System.out.println("2D: " + Arrays.deepToString(mat));
        // [[1, 2], [3, 4]]
    }
}
Arrays.sort() uses Dual-Pivot Quicksort for primitives (O(n log n) average) and TimSort for objects (stable sort). In competitive programming, always use Arrays.sort() — never write your own sort unless the problem requires it. It's been optimised by Java engineers over 25 years.

11. Variable Arguments (Varargs)

Varargs let a method accept zero or more arguments of a specified type. Internally, Java converts them into an array. The syntax is Type... name.

Java
public class VarargsDemo {

    // Method accepts variable number of int arguments
    public static int sum(int... nums) {
        int total = 0;
        for (int n : nums) {
            total += n;
        }
        return total;
    }

    public static void main(String[] args) {
        System.out.println(sum(10, 20));              // 30
        System.out.println(sum(1, 2, 3, 4, 5));       // 15
        System.out.println(sum());                    // 0
    }
}
Varargs must be the LAST parameter. void foo(int... nums, String s) is ILLEGAL and won't compile. Correct: void foo(String s, int... nums). You can have only ONE varargs parameter per method.

12. Enumerations (enum)

An enum defines a fixed set of constants. Instead of using magic numbers like 1 for Monday or 2 for Tuesday, you use meaningful names that the compiler can check.

Enum = IRCTC train class — fixed constants: SL, 3A, 2A, 1A, CC. You can't invent a new class called "5A" — it simply doesn't exist. Similarly, Java enums restrict values to only the ones you define. This prevents bugs caused by invalid values creeping into your code.

Full Program: DayOfWeekEnum

Java
enum Day {
    MONDAY("Work", 8),
    TUESDAY("Work", 8),
    WEDNESDAY("Work", 8),
    THURSDAY("Work", 8),
    FRIDAY("Work", 7),
    SATURDAY("Half-day", 4),
    SUNDAY("Holiday", 0);

    private final String type;
    private final int hours;

    // Enum constructor (always private)
    Day(String type, int hours) {
        this.type = type;
        this.hours = hours;
    }

    public String getType() { return type; }
    public int getHours() { return hours; }
}

public class DayOfWeekEnum {
    public static void main(String[] args) {
        // Using enum in switch
        Day today = Day.FRIDAY;
        switch (today) {
            case MONDAY: case TUESDAY: case WEDNESDAY:
            case THURSDAY: case FRIDAY:
                System.out.println("It's a workday!");
                break;
            case SATURDAY: case SUNDAY:
                System.out.println("Weekend! 🎉");
                break;
        }

        // Enum methods
        System.out.println("Name:    " + today.name());       // FRIDAY
        System.out.println("Ordinal: " + today.ordinal());    // 4
        System.out.println("Type:    " + today.getType());   // Work
        System.out.println("Hours:   " + today.getHours());  // 7

        // values() — iterate all constants
        System.out.println("\n--- Weekly Schedule ---");
        for (Day d : Day.values()) {
            System.out.printf("%-10s : %s (%d hrs)%n", d.name(), d.getType(), d.getHours());
        }
    }
}
It's a workday! Name: FRIDAY Ordinal: 4 Type: Work Hours: 7 --- Weekly Schedule --- MONDAY : Work (8 hrs) TUESDAY : Work (8 hrs) WEDNESDAY : Work (8 hrs) THURSDAY : Work (8 hrs) FRIDAY : Work (7 hrs) SATURDAY : Half-day (4 hrs) SUNDAY : Holiday (0 hrs)
Enum MethodReturnsExample
name()The constant name as StringDay.MONDAY.name()"MONDAY"
ordinal()The position (0-based)Day.MONDAY.ordinal()0
values()Array of all constantsDay.values()Day[7]
valueOf(String)Enum constant from nameDay.valueOf("FRIDAY")Day.FRIDAY

13. EnumSet & EnumMap

Java
import java.util.EnumSet;
import java.util.EnumMap;

enum TrainClass { SL, AC3, AC2, AC1, CC, EC }

public class EnumCollections {
    public static void main(String[] args) {
        // EnumSet — high-performance Set for enums
        EnumSet<TrainClass> acClasses = EnumSet.of(TrainClass.AC3, TrainClass.AC2, TrainClass.AC1);
        System.out.println("AC Classes: " + acClasses);
        // [AC3, AC2, AC1]

        EnumSet<TrainClass> allClasses = EnumSet.allOf(TrainClass.class);
        System.out.println("All: " + allClasses);

        // EnumMap — Map with enum keys (faster than HashMap)
        EnumMap<TrainClass, Integer> fares = new EnumMap<>(TrainClass.class);
        fares.put(TrainClass.SL, 350);
        fares.put(TrainClass.AC3, 950);
        fares.put(TrainClass.AC2, 1400);
        fares.put(TrainClass.AC1, 2500);
        fares.put(TrainClass.CC, 750);
        fares.put(TrainClass.EC, 1800);

        System.out.println("\nIRCTC Fare Chart (Delhi → Mumbai):");
        for (var entry : fares.entrySet()) {
            System.out.printf("  %s : ₹%d%n", entry.getKey(), entry.getValue());
        }
    }
}
EnumMap is 2–3× faster than HashMap when keys are enums. It uses an internal array indexed by ordinal values. Always prefer EnumMap and EnumSet when working with enum types — this is a common interview follow-up question.

14. Full Program: NiftyPriceArrayProcessor

Java
import java.util.Arrays;

public class NiftyPriceArrayProcessor {
    public static void main(String[] args) {
        // 30 days of Nifty 50 closing prices (simulated)
        double[] prices = {
            22150.5, 22230.1, 22180.3, 22310.7, 22450.2,
            22380.9, 22520.4, 22490.8, 22610.3, 22580.6,
            22700.1, 22650.5, 22780.2, 22820.9, 22750.3,
            22900.7, 22850.4, 22980.1, 23050.6, 22990.3,
            23120.8, 23080.2, 23200.5, 23150.9, 23300.1,
            23250.7, 23380.4, 23420.2, 23350.8, 23500.6
        };

        // 1. Highest and Lowest price
        double highest = prices[0], lowest = prices[0];
        int highDay = 0, lowDay = 0;
        for (int i = 1; i < prices.length; i++) {
            if (prices[i] > highest) { highest = prices[i]; highDay = i; }
            if (prices[i] < lowest)  { lowest = prices[i];  lowDay = i; }
        }

        // 2. Average price
        double sum = 0;
        for (double p : prices) sum += p;
        double average = sum / prices.length;

        // 3. 5-day Simple Moving Average (SMA)
        System.out.println("=== NIFTY 50 — 30-Day Analysis ===");
        System.out.printf("Highest: ₹%.2f (Day %d)%n", highest, highDay + 1);
        System.out.printf("Lowest:  ₹%.2f (Day %d)%n", lowest, lowDay + 1);
        System.out.printf("Average: ₹%.2f%n%n", average);

        System.out.println("5-Day SMA:");
        for (int i = 4; i < prices.length; i++) {
            double sma = 0;
            for (int j = i - 4; j <= i; j++) {
                sma += prices[j];
            }
            sma /= 5.0;
            System.out.printf("  Day %2d: ₹%.2f%n", i + 1, sma);
        }

        // 4. Days above average
        int aboveAvg = 0;
        for (double p : prices) {
            if (p > average) aboveAvg++;
        }
        System.out.printf("%nDays above average: %d / %d%n", aboveAvg, prices.length);
    }
}
=== NIFTY 50 — 30-Day Analysis === Highest: ₹23500.60 (Day 30) Lowest: ₹22150.50 (Day 1) Average: ₹22810.55 5-Day SMA: Day 5: ₹22264.16 Day 6: ₹22310.44 Day 7: ₹22368.50 ... Day 30: ₹23380.34 Days above average: 16 / 30
Zerodha's Kite platform calculates moving averages in real time for all 1,500+ listed stocks on NSE. Each stock has arrays of tick data (price + volume) refreshed every second. The SMA, EMA, RSI, and MACD indicators you see on charts are all computed using loops over price arrays — exactly like the NiftyPriceArrayProcessor above, just at massive scale.
Section D

Learn by Doing — 3-Tier Lab: Nifty Stock Price Analyzer

🟢 Tier 1 — GUIDED TASK: Basic Stock Price Array Processor

⏱️ 45–60 minutesBeginnerStep-by-step instructions

Step 1: Create the Class

Open your IDE (IntelliJ / VS Code). Create a new file StockAnalyzer.java.

Step 2: Declare the Price Array

Java
public class StockAnalyzer {
    public static void main(String[] args) {
        double[] prices = {1520.5, 1535.2, 1498.7, 1550.0, 1480.3,
                           1575.8, 1560.1, 1590.4, 1510.6, 1605.9};
    }
}

Step 3: Find Maximum Price

Add a for loop to find the highest price and which day it occurred on:

Java
double max = prices[0];
int maxDay = 1;
for (int i = 1; i < prices.length; i++) {
    if (prices[i] > max) {
        max = prices[i];
        maxDay = i + 1;
    }
}
System.out.println("Highest: ₹" + max + " on Day " + maxDay);

Step 4: Find Minimum Price

Copy the max logic, but change > to < and variable names to min/minDay.

Step 5: Calculate Average

Java
double sum = 0;
for (double p : prices) sum += p;
double avg = sum / prices.length;
System.out.printf("Average: ₹%.2f%n", avg);

Step 6: Count Gain Days

Java
int gainDays = 0;
for (int i = 1; i < prices.length; i++) {
    if (prices[i] > prices[i-1]) gainDays++;
}
System.out.println("Gain days: " + gainDays + " out of " + (prices.length-1));

Step 7: Compile and Run

🎉 Congratulations! You've built your first stock analyzer. This logic is what runs inside every trading terminal in India.

🟡 Tier 2 — SEMI-GUIDED: Moving Average & Trend Detection

⏱️ 60–90 minutesIntermediateHints provided

Your Mission:

Extend Tier 1 to include a 3-day moving average and trend detection (uptrend/downtrend).

Hints:

  1. 3-Day SMA: For each day i (starting from index 2), calculate (prices[i-2] + prices[i-1] + prices[i]) / 3.0
  2. Trend Detection: If the SMA is increasing for 3+ consecutive days, print "📈 UPTREND detected." If decreasing for 3+ days, print "📉 DOWNTREND detected."
  3. Daily Change %: For each day, calculate ((prices[i] - prices[i-1]) / prices[i-1]) * 100 and flag days with >2% change as "⚠️ High volatility"
  4. Sort & Display: Use Arrays.copyOf() to create a sorted copy (don't modify original), then display the sorted prices
Stretch Goal: Add an Exponential Moving Average (EMA). Formula: EMA_today = price_today × (2/(period+1)) + EMA_yesterday × (1 - 2/(period+1)). Compare SMA vs EMA visually.

🔴 Tier 3 — OPEN CHALLENGE: Multi-Stock Portfolio Tracker

⏱️ 2–3 hoursAdvancedNo instructions — design it yourself

The Brief:

Build a complete portfolio tracker that handles multiple stocks. Requirements:

  1. Create an enum Sector { IT, BANKING, PHARMA, AUTO, FMCG } with properties
  2. Use a 2D array: double[][] portfolio — rows = stocks, columns = daily prices
  3. Track at least 5 stocks (Infosys, HDFC, Sun Pharma, Tata Motors, HUL) over 10 days
  4. Calculate per-stock: max, min, average, total return %
  5. Calculate portfolio-level: best performer, worst performer, sector-wise average returns
  6. Display results as a formatted table using System.out.printf()
  7. Use EnumMap<Sector, Double> for sector-wise return mapping

Deliverable: A single PortfolioTracker.java file that compiles and runs with sample data. This is a portfolio-worthy project for your GitHub.

Stock screening tools are in huge demand. Many Indian traders on Zerodha/Groww forums look for custom screeners. A Java developer who can build stock analysis tools can offer freelance services to algo-trading communities — ₹5,000–₹20,000 per tool.
Section E

Problem Set — Practice & Interview Prep

Syntax / Debug Questions (5)

S1. Find the error:

Java
int[] arr = new int[5];
for (int i = 0; i <= 5; i++) {
    arr[i] = i * 2;
}

Answer: ArrayIndexOutOfBoundsException at i=5. Condition should be i < 5 or i < arr.length.

S2. Find the error:

Java
int x = 10;
while (x > 0) {
    System.out.println(x);
}

Answer: Infinite loop — x is never decremented. Add x--; inside the loop body.

S3. Find the error:

Java
int[] nums = {1, 2, 3};
for (int n : nums) {
    n = n * 2;
}
System.out.println(Arrays.toString(nums));

Answer: Output is still [1, 2, 3]. Enhanced for-each creates a copy of each element — modifying n doesn't change the original array. Use a traditional for loop with index to modify array elements.

S4. Find the error:

Java
public static void print(String... args, int count) { }

Answer: Varargs must be the LAST parameter. Correct: void print(int count, String... args).

S5. What's the output?

Java
int i = 0;
do {
    System.out.print(i + " ");
    i++;
} while (i < 0);

Answer: Output is 0. The do-while executes the body at least once before checking the condition. After printing 0 and incrementing to 1, the condition 1 < 0 is false, so the loop exits.

Programming Problems (8)

P1. Easy — Reverse an Array

Write a method void reverseArray(int[] arr) that reverses the array in-place using two pointers (start and end).

P2. Easy — Find Duplicates

Given an array of integers, print all duplicate elements. Example: {1,3,5,3,7,1} → Output: 1, 3.

P3. Medium — Rotate Array

Rotate an array to the right by k positions. Example: {1,2,3,4,5}, k=2 → {4,5,1,2,3}. Hint: Use three reverses.

P4. Medium — Frequency Count

Given an array, print each element with its frequency. Example: {4,2,4,5,2,4}4 appears 3 times, 2 appears 2 times, 5 appears 1 time.

P5. Medium — Merge Two Sorted Arrays

Given two sorted arrays, merge them into a single sorted array without using Arrays.sort().

P6. Medium — Matrix Transpose

Write a program to find the transpose of a 3×3 matrix (swap rows and columns).

P7. Hard — Two Sum

Given an array and a target sum, find two indices whose values add up to the target. Example: {2,7,11,15}, target=9 → Output: [0, 1] (because 2+7=9). Aim for O(n) using a HashMap.

P8. Hard — Maximum Subarray (Kadane's Algorithm)

Find the contiguous subarray with the largest sum. Example: {-2,1,-3,4,-1,2,1,-5,4} → Output: 6 (subarray {4,-1,2,1}).

Java
// Kadane's Algorithm — O(n) time, O(1) space
public static int maxSubArray(int[] nums) {
    int maxSoFar = nums[0];
    int maxEndingHere = nums[0];

    for (int i = 1; i < nums.length; i++) {
        maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
        maxSoFar = Math.max(maxSoFar, maxEndingHere);
    }
    return maxSoFar;
}

Industry-Relevant Problems (3)

I1. Stock Price Daily Returns

Given an array of stock prices over 30 days, calculate the daily return percentage for each day, find the best and worst days, and calculate the overall 30-day return.

I2. Student Grade Distribution

Given marks of 50 students, create a frequency distribution: how many scored 0–20, 21–40, 41–60, 61–80, 81–100. Display the distribution using a text-based bar chart (using * characters).

I3. Enum-Based Menu System

Build a railway booking menu using enum TrainClass {SL, AC3, AC2, AC1, CC} with base fares. Let the user select a class, enter distance, and calculate total fare = baseFare × (distance/100). Use a do-while loop for repeated bookings.

Interview Questions (3)

IQ1. Explain Kadane's Algorithm step by step. What is its time and space complexity? Can it handle arrays with all negative numbers?

Model Answer: Kadane's Algorithm maintains two variables: maxEndingHere (maximum subarray sum ending at the current index) and maxSoFar (global maximum). At each element, we decide: either start a new subarray at the current element or extend the previous subarray. Time: O(n), Space: O(1). Yes, it handles all-negative arrays — it returns the least negative number (the "largest" sum possible).

IQ2. When would you choose an array over an ArrayList? Give 3 scenarios with reasoning.

Model Answer: (1) When size is fixed and known at compile time — arrays avoid resizing overhead. (2) For primitive types (int, double) — arrays store primitives directly; ArrayList requires autoboxing to wrapper objects (Integer, Double), wasting memory. (3) For performance-critical inner loops — array access is ~2× faster than ArrayList due to no bounds checking overhead and better cache locality.

IQ3. What is the Singleton pattern using enum? Why is it considered the best implementation?

Model Answer: An enum with a single constant acts as a Singleton: enum Database { INSTANCE; }. It's the best approach because: (1) Thread-safe by default (JVM guarantees single instantiation). (2) Serialization-safe (no duplicate instances after deserialization). (3) Prevents reflection attacks. (4) Concise — no boilerplate code. Joshua Bloch (Effective Java) calls it "the best way to implement a singleton."

Section F

MCQ Assessment Bank — 30 Questions (Bloom's Mapped)

Remember / Identify (Q1–Q5)

Q1

Which loop in Java checks the condition AFTER executing the body?

  1. for
  2. while
  3. do-while
  4. enhanced for
Remember
✅ Answer: (C) do-while — The do-while loop executes the body first, then checks the condition. This guarantees at least one execution.
Q2

What is the default value of elements in a newly created int array in Java?

  1. null
  2. -1
  3. 0
  4. undefined
Remember
✅ Answer: (C) 0 — All numeric array elements default to 0 (int, double, etc.), boolean defaults to false, and object references default to null.
Q3

Which keyword is used to define an enumeration in Java?

  1. enumerate
  2. Enum
  3. enum
  4. const
Remember
✅ Answer: (C) enum — The lowercase enum keyword is used. Enum (capital E) is the base class, not the keyword.
Q4

What does arr.length return for int[] arr = {10, 20, 30, 40, 50};?

  1. 4
  2. 5
  3. 6
  4. Compilation error
Remember
✅ Answer: (B) 5 — The length field returns the total number of elements in the array, not the last index.
Q5

Which syntax correctly declares a varargs parameter?

  1. int[] nums
  2. int... nums
  3. int* nums
  4. int nums...
Remember
✅ Answer: (B) int... nums — The three dots come after the type and before the variable name. This is Java's varargs syntax.

Understand / Explain (Q6–Q10)

Q6

Why does an enhanced for-each loop NOT allow modification of array elements?

  1. It uses a read-only copy of each element
  2. Arrays are immutable in Java
  3. The JVM locks the array during iteration
  4. It only works with final arrays
Understand
✅ Answer: (A) — The for-each loop copies each element's value to the loop variable. Modifying the loop variable changes the copy, not the original array element.
Q7

What happens when you access arr[arr.length]?

  1. Returns the last element
  2. Returns 0
  3. Throws ArrayIndexOutOfBoundsException
  4. Returns null
Understand
✅ Answer: (C) — Valid indices are 0 to arr.length - 1. Index arr.length is out of bounds and throws ArrayIndexOutOfBoundsException at runtime.
Q8

What does ordinal() return for the FIRST constant defined in an enum?

  1. 1
  2. 0
  3. -1
  4. The constant's hash code
Understand
✅ Answer: (B) 0 — Enum ordinal values are zero-based. The first constant has ordinal 0, second has 1, and so on.
Q9

Why is while preferred over for when reading user input until a sentinel value?

  1. while loops are faster
  2. The number of iterations is unknown in advance
  3. for loops cannot read input
  4. while loops use less memory
Understand
✅ Answer: (B) — While loops are ideal when the number of iterations depends on a runtime condition (like user input). For loops are better when the count is known beforehand.
Q10

In a 2D array int[][] m = new int[3][4];, what does m.length and m[0].length return?

  1. 4 and 3
  2. 3 and 4
  3. 12 and 4
  4. 3 and 3
Understand
✅ Answer: (B) — m.length returns the number of rows (3). m[0].length returns the number of columns in the first row (4).

Apply / Trace Output (Q11–Q15)

Q11

What is the output?
for(int i=1; i<=5; i++) { if(i==3) continue; System.out.print(i+" "); }

  1. 1 2 3 4 5
  2. 1 2 4 5
  3. 1 2
  4. 3
Apply
✅ Answer: (B) 1 2 4 5 — The continue statement skips the current iteration when i==3, so 3 is not printed.
Q12

What is the output?
int[] a = {10,20,30}; System.out.println(a);

  1. [10, 20, 30]
  2. 10 20 30
  3. Something like [I@1a2b3c4
  4. Compilation error
Apply
✅ Answer: (C) — Printing an array directly outputs its hash code (type@hashcode). Use Arrays.toString(a) to print readable contents.
Q13

After executing: int[] x = {5,3,8,1}; Arrays.sort(x); what is x[2]?

  1. 8
  2. 3
  3. 5
  4. 1
Apply
✅ Answer: (C) 5 — After sorting, the array becomes {1, 3, 5, 8}. Index 2 holds the value 5.
Q14

What is the output?
int i=5; do { System.out.print(i+" "); i--; } while(i>5);

  1. No output
  2. 5
  3. 5 4 3 2 1
  4. Infinite loop
Apply
✅ Answer: (B) 5 — The do-while executes once (printing 5), then checks 4>5 which is false, so the loop exits.
Q15

What does Arrays.fill(new int[4], 7) produce?

  1. {0, 0, 0, 0}
  2. {7, 7, 7, 7}
  3. {7, 0, 0, 0}
  4. Compilation error
Apply
✅ Answer: (B) {7, 7, 7, 7} — Arrays.fill() fills all elements of the array with the specified value.

Apply / Code Completion (Q16–Q20)

Q16

Complete the blank to iterate backwards: for(int i = arr.length-1; i ___ 0; i--)

  1. >
  2. >=
  3. <
  4. !=
Apply
✅ Answer: (B) >= — To include index 0 (the first element), we need i >= 0. Using i > 0 would skip the first element.
Q17

Which method returns an array of all constants in an enum?

  1. constants()
  2. getAll()
  3. values()
  4. enumerate()
Apply
✅ Answer: (C) values() — The compiler auto-generates the values() method for every enum, returning an array of all constants in declaration order.
Q18

What happens if you call Arrays.binarySearch() on an unsorted array?

  1. It sorts first, then searches
  2. Returns -1
  3. Result is undefined (unpredictable)
  4. Throws an exception
Apply
✅ Answer: (C) — Binary search requires a sorted array. Using it on an unsorted array gives unpredictable results (it doesn't throw an error or sort automatically).
Q19

Which is valid for the enhanced for loop?

  1. for (int x : 5)
  2. for (int x : arr)
  3. for (arr : int x)
  4. for (int x in arr)
Apply
✅ Answer: (B) — Syntax is for (Type variable : array/collection). Java uses : not in.
Q20

Given void foo(String label, int... nums), which call is INVALID?

  1. foo("test", 1, 2, 3)
  2. foo("test")
  3. foo("test", new int[]{1,2})
  4. foo(1, 2, "test")
Apply
✅ Answer: (D) — The String parameter must come first. Option D puts integers before the String, which doesn't match the method signature.

Analyze / Compare (Q21–Q25)

Q21

Which loop type is most suitable for reading lines from a file until EOF?

  1. for loop
  2. do-while loop
  3. while loop
  4. enhanced for loop
Analyze
✅ Answer: (C) while — The number of lines is unknown until we reach EOF. A while loop with scanner.hasNextLine() naturally handles this.
Q22

Why might you prefer int[] over ArrayList<Integer> in a performance-critical loop?

  1. Arrays support generics
  2. Arrays avoid autoboxing overhead and have better cache locality
  3. ArrayList doesn't support iteration
  4. Arrays can grow dynamically
Analyze
✅ Answer: (B) — Primitive arrays store values directly in contiguous memory (better cache locality). ArrayList<Integer> stores wrapper objects with autoboxing/unboxing overhead, making it slower.
Q23

What is the bug?
for(int i=0; i<10; i++) { if(i%2==0) continue; System.out.print(i); } // Intent: print even numbers

  1. Prints odd numbers instead of even
  2. Infinite loop
  3. Compilation error
  4. Prints nothing
Analyze
✅ Answer: (A) — The continue SKIPS even numbers (when i%2==0). To print even numbers, use if(i%2 != 0) continue; or remove continue and use an if block.
Q24

In which scenario is an enum clearly better than static final int constants?

  1. When you need to store large numbers
  2. When you need type safety and want to prevent invalid values
  3. When you need dynamic values at runtime
  4. When memory is extremely limited
Analyze
✅ Answer: (B) — Enums provide compile-time type safety. With static final int, any integer value can be passed, but with enums, only valid constants are accepted by the compiler.
Q25

What is the time complexity of finding the maximum element in an unsorted array of n elements?

  1. O(1)
  2. O(log n)
  3. O(n)
  4. O(n²)
Analyze
✅ Answer: (C) O(n) — You must check every element once to guarantee finding the maximum. No shortcut exists for unsorted data.

Evaluate / Create (Q26–Q30)

Q26

Which approach is MOST efficient to find if a value exists in a sorted array of 1 million elements?

  1. Linear search with for loop
  2. Arrays.binarySearch()
  3. Enhanced for-each loop
  4. Converting to ArrayList and using .contains()
Evaluate
✅ Answer: (B) — Binary search is O(log n) ≈ 20 comparisons for 1 million elements. Linear search is O(n) = up to 1 million comparisons. Always use binary search on sorted data.
Q27

A student writes: enum Color { RED, GREEN, BLUE; public Color() {} }. What happens?

  1. Compiles and runs fine
  2. Compilation error — enum constructors cannot be public
  3. Runtime exception
  4. Prints RED GREEN BLUE
Evaluate
✅ Answer: (B) — Enum constructors must be private or package-private. Public constructors are illegal because enums should not be instantiated outside their declaration.
Q28

Which design pattern is BEST implemented using a single-constant enum?

  1. Factory
  2. Observer
  3. Singleton
  4. Strategy
Create
✅ Answer: (C) Singleton — enum Singleton { INSTANCE; } is the recommended Singleton implementation (Joshua Bloch, Effective Java). It's thread-safe, serialization-safe, and reflection-proof.
Q29

To store daily temperatures for 12 months × 30 days, the best structure is:

  1. int[] temps = new int[360];
  2. int[][] temps = new int[12][30];
  3. ArrayList<Integer> temps;
  4. int temps;
Create
✅ Answer: (B) — A 2D array naturally maps to months (rows) and days (columns), making access like temps[month][day] intuitive and efficient.
Q30

Kadane's Algorithm for Maximum Subarray has which complexity?

  1. O(n²) time, O(n) space
  2. O(n log n) time, O(1) space
  3. O(n) time, O(1) space
  4. O(n) time, O(n) space
Evaluate
✅ Answer: (C) O(n) time, O(1) space — Kadane's uses a single pass through the array with only two variables (maxSoFar, maxEndingHere), making it optimal for both time and space.
Section G

Short Answer Questions (8)

SA1. What is the difference between a for loop and a while loop? When would you use each?

Answer: A for loop is used when the number of iterations is known in advance (e.g., iterating an array of known size). A while loop is preferred when iteration count depends on a runtime condition (e.g., reading user input until a sentinel value). The for loop combines initialization, condition, and update in one line, while while separates them. Functionally, any for loop can be rewritten as a while loop and vice versa.

SA2. Compare arrays and ArrayList in Java. Give two advantages of each.

Answer: Arrays are fixed-size, support primitives (no autoboxing overhead), and have faster access (better cache locality). ArrayList is dynamically resizable and provides utility methods like add(), remove(), contains(), and indexOf(). Use arrays for performance-critical code with known sizes; use ArrayList when you need dynamic sizing or frequent insertions/deletions.

SA3. Why are enums preferred over public static final int constants?

Answer: Enums provide compile-time type safety — the compiler prevents invalid values. With static final int, any integer can be passed where a constant is expected, leading to hard-to-find bugs. Enums also support methods, constructors, and fields, making them more powerful. Additionally, enums work naturally with switch statements and provide built-in values() and valueOf() methods.

SA4. What are the rules for using varargs in Java?

Answer: (1) Varargs must be the last parameter in the method signature. (2) Only one varargs parameter is allowed per method. (3) Internally, Java treats varargs as an array. (4) You can pass zero or more arguments, or even an actual array. The syntax is Type... paramName.

SA5. Explain ArrayIndexOutOfBoundsException with an example.

Answer: This runtime exception occurs when you try to access an array element using an invalid index — either negative or greater than or equal to array.length. For example, int[] a = new int[3]; a[3] = 10; throws this exception because valid indices are 0, 1, 2. This is a very common bug caused by off-by-one errors in loop conditions.

SA6. What are the limitations of the enhanced for-each loop?

Answer: (1) You cannot modify array elements because the loop variable is a copy, not a reference to the original element. (2) You don't have access to the current index. (3) You can only traverse forward, not backward. (4) You cannot iterate over multiple arrays simultaneously. Use a traditional for loop when any of these are needed.

SA7. What is the difference between break and continue?

Answer: break immediately exits the entire loop (or switch), and execution continues after the loop. continue skips the remaining body of the current iteration and jumps to the next iteration. In nested loops, both affect only the innermost loop unless a labeled break/continue is used.

SA8. What sorting algorithm does Arrays.sort() use internally?

Answer: For primitive arrays (int, double, etc.), Arrays.sort() uses Dual-Pivot Quicksort (average O(n log n), not stable). For object arrays (String, Integer, custom objects), it uses TimSort (O(n log n), stable). TimSort is a hybrid of Merge Sort and Insertion Sort, optimised for real-world data with partially sorted runs.

Section H

Long Answer Questions (3)

LA1. Explain all loop types in Java with syntax, examples, and when to use each.

Model Answer:

Java provides four loop constructs: for, enhanced for-each, while, and do-while.

The for loop has the syntax for(init; condition; update) { body }. It's ideal when the iteration count is known, such as iterating through an array of known size or counting from 1 to N. Example: for(int i=0; i<10; i++) executes exactly 10 times.

The enhanced for-each loop uses syntax for(Type var : array) { body }. It simplifies array/collection traversal by eliminating index management. However, it cannot modify elements, access the index, or traverse backwards. Use it for read-only traversals.

The while loop uses syntax while(condition) { body }. The condition is checked before each iteration, so the body may never execute. It's best for input validation, reading until EOF, or any situation where the number of iterations is unknown.

The do-while loop uses syntax do { body } while(condition);. The body executes at least once because the condition is checked after execution. It's ideal for menu-driven programs, input validation with at least one prompt, and situations requiring guaranteed first execution.

Java also supports loop control with break (exit loop), continue (skip iteration), and labeled break (exit outer loop from nested loops). All loops can be nested for multi-dimensional data processing like matrix operations. In practice, the for loop is most common (used in ~60% of cases), followed by while (~25%), enhanced for (~12%), and do-while (~3%).

LA2. Explain arrays in Java — 1D, 2D, and the java.util.Arrays utility class with code examples.

Model Answer:

Arrays in Java are fixed-size, homogeneous data structures that store elements in contiguous memory. They are objects created with the new keyword or initialized with curly braces.

A 1D array is declared as int[] arr = new int[5]; or int[] arr = {1,2,3,4,5};. Elements are accessed via zero-based indices: arr[0] to arr[arr.length-1]. Arrays can be passed to methods and returned from methods. Default values are 0 for numeric types, false for boolean, and null for references.

A 2D array is an array of arrays: int[][] matrix = new int[3][4]; creates a 3-row, 4-column matrix. Access uses double indexing: matrix[row][col]. matrix.length gives rows, matrix[0].length gives columns. Java supports jagged arrays where each row can have a different number of columns.

The java.util.Arrays class provides essential static utility methods. Arrays.sort(arr) sorts in ascending order using Dual-Pivot Quicksort. Arrays.binarySearch(arr, key) finds elements in O(log n) time but requires a pre-sorted array. Arrays.fill(arr, val) sets all elements to a specified value. Arrays.copyOf(arr, newLen) creates a copy with the specified length. Arrays.toString(arr) returns a readable string representation, and Arrays.deepToString(arr2D) works for multi-dimensional arrays. Arrays.equals(a, b) compares content of two arrays. These methods eliminate boilerplate code and are highly optimised — always prefer them over manual implementations.

LA3. Explain Java enumerations — defining, using, built-in methods, and advanced features (EnumSet, EnumMap) with a real-world use case.

Model Answer:

Java enumerations (enum) define a type with a fixed set of named constants. They replace error-prone integer constants with type-safe, self-documenting values. An enum is declared as: enum Day { MONDAY, TUESDAY, ... SUNDAY }.

Enums in Java are much more powerful than in most languages. They can have constructors, fields, and methods. For example, enum TrainClass { SL(350), AC3(950); private int fare; TrainClass(int fare) { this.fare = fare; } } associates a fare with each class. Constructors are implicitly private.

Built-in methods include: name() returns the constant name as a String; ordinal() returns the zero-based position; values() returns an array of all constants; valueOf(String) converts a name back to the enum constant.

Enums work seamlessly with switch statements and can implement interfaces, making them useful for strategy patterns. The Singleton design pattern is best implemented with a single-constant enum: enum Database { INSTANCE; }.

EnumSet is a high-performance Set implementation for enums, using a bit vector internally. EnumSet.of(Day.MONDAY, Day.FRIDAY) creates a set with O(1) operations. EnumMap is a Map with enum keys, 2-3× faster than HashMap because it uses an ordinal-indexed array internally.

Real-world example: In an IRCTC-like booking system, enum TrainClass with SL, 3A, 2A, 1A, CC constants ensures that no invalid booking class can enter the system. Each constant stores its base fare, availability limit, and comfort level. An EnumMap maps each class to its real-time availability count, and an EnumSet stores the set of classes available for a specific train.

Section I

Lab Programs

Lab programs for this unit are covered in Section D — Learn by Doing. Complete all 3 tiers for full lab credit:

  • Tier 1 (Guided): Basic Stock Price Array Processor — find max, min, average, gain days
  • Tier 2 (Semi-guided): Moving Average & Trend Detection — SMA, volatility, sorted display
  • Tier 3 (Open Challenge): Multi-Stock Portfolio Tracker — 2D arrays, enums, EnumMap, formatted output

Additionally, the following full programs in Section C serve as lab references:

  • StudentMarksAnalyzer.java — 1D array processing with statistics
  • MatrixMultiplier.java — 2D array matrix multiplication
  • NiftyPriceArrayProcessor.java — Stock analysis with SMA
  • DayOfWeekEnum.java — Enum with properties and methods
Section J

Industry Spotlight — A Day in the Life

👨‍💻 Arjun Mehta, 27 — Backend Developer at Amazon India, Hyderabad

Background: B.Tech in Computer Science from a tier-2 college in Pune. Started competitive programming on CodeChef in 2nd year. Self-taught Java through NPTEL and YouTube. Built a stock portfolio tracker as a college project. Got placed at Amazon through an off-campus drive after clearing 4 rounds of DSA interviews.

A Typical Day:

9:30 AM — Morning standup with the Inventory Management team. Discuss yesterday's deployment and today's sprint tasks.

10:00 AM — Write Java code for a new inventory rebalancing feature. Uses arrays of warehouse stock levels across 50+ fulfilment centres. Loops through each centre to calculate reorder quantities based on demand forecasts.

11:30 AM — Code review session. Review a colleague's PR that uses an enum OrderStatus { PLACED, CONFIRMED, SHIPPED, DELIVERED, RETURNED, CANCELLED } with an EnumMap for state transitions.

1:00 PM — Lunch at Amazon's cafeteria. Quick LeetCode problem solving with friends (today: Maximum Subarray — Kadane's Algorithm).

2:00 PM — Fix a bug where a for loop was using <= instead of < on an inventory array, causing ArrayIndexOutOfBoundsException in production for 0.01% of requests.

4:00 PM — Design a new feature: category-based product filtering using enum Category { ELECTRONICS, BOOKS, FASHION, GROCERY } with EnumSet for multi-category selections.

6:00 PM — Write unit tests using JUnit. Test edge cases: empty arrays, single-element arrays, arrays with all identical values.

DetailInfo
Tools Used DailyJava 17, IntelliJ IDEA, Git, AWS (Lambda, DynamoDB), JUnit, Gradle
Entry Salary (2024)₹6–10 LPA + RSUs + benefits
Mid-Level (3–5 yrs)₹12–22 LPA
Senior (7+ yrs)₹25–50 LPA
Companies HiringAmazon, Flipkart, Google, Microsoft, Paytm, Razorpay, PhonePe, Zerodha, Atlassian, Goldman Sachs
Arjun's advice to students: "Every single interview I've given — Amazon, Google, Flipkart — has asked at least one array problem. Two Sum, Maximum Subarray, Rotate Array — these are bread and butter. Master arrays and loops first. Everything else (trees, graphs, DP) builds on top of them."
Section K

Earn With It — Freelance & Income Roadmap

💰 Your Earning Path After This Chapter

Portfolio Pieces: StockAnalyzer.java + MatrixMultiplier.java + DayOfWeekEnum.java — push to GitHub with README.

Earning Opportunities:

Competitive Programming Tutoring: Teach loops, arrays, and basic DSA on Unacademy/Topmate — ₹5,000–₹20,000/month

YouTube Content: Create "Java DSA for Beginners" series — ad revenue + affiliate income after 1000 subscribers

Freelance Java Projects: Build data processing tools, CSV parsers, report generators — ₹3,000–₹15,000/project

College Assignment Help: (Ethical tutoring, not copy-paste) Help juniors understand loops/arrays — ₹200–₹500/session

PlatformBest ForTypical Rate
Topmate1-on-1 DSA mentoring sessions₹300–₹1,000/session
UnacademyTeaching programming to large audience₹5,000–₹20,000/month
YouTubeTutorial videos on Java/DSA₹2,000–₹50,000/month (after growth)
InternshalaJava development internships₹5,000–₹15,000/month
FiverrSmall Java projects for global clients$20–$100/project (₹1,600–₹8,000)

⏱️ Time to First Earning: 2–4 weeks (if you solve 50+ LeetCode problems and create 5 tutorial videos or offer mentoring sessions)

The competitive programming community in India is massive. CodeChef, Codeforces, and LeetCode have millions of Indian users. If you can explain concepts clearly, there's always demand for tutoring. Start by helping 5 friends for free → collect testimonials → launch paid sessions on Topmate.
Section L

Chapter Summary

🎯 Key Takeaways — Unit 5

  • for loop: Best when iteration count is known. Syntax: for(init; cond; update)
  • Enhanced for-each: Read-only array traversal. Syntax: for(Type var : array)
  • while loop: Condition-first; best for unknown iteration count
  • do-while loop: Body-first; guarantees at least one execution
  • break/continue: Control flow within loops; labeled break exits outer loops
  • 1D Arrays: Fixed-size, 0-indexed, stored in contiguous memory
  • 2D Arrays: Array of arrays; used for matrices, grids, tables
  • java.util.Arrays: sort(), binarySearch(), fill(), copyOf(), toString()
  • Varargs: Type... name; must be last param; treated as array internally
  • Enum: Type-safe constants with constructors, fields, and methods
  • EnumSet/EnumMap: High-performance collections for enum types
  • Kadane's Algorithm: Maximum subarray in O(n) time — top interview question

📝 Code Tweet (280 chars)

Java loops + arrays = 80% of all code you'll ever write. for/while/do-while iterate. int[] stores. Arrays.sort() optimizes. enum fixes constants. Kadane's finds max subarray in O(n). Master these → clear any DSA interview. #JavaUnit5 #EduArtha

Quick Reference — Syntax Cheat Sheet

ConceptSyntax
for loopfor (int i = 0; i < n; i++) { }
for-eachfor (int x : arr) { }
whilewhile (condition) { }
do-whiledo { } while (condition);
1D Arrayint[] arr = new int[n]; or {1,2,3}
2D Arrayint[][] m = new int[r][c];
SortArrays.sort(arr);
SearchArrays.binarySearch(sortedArr, key);
PrintArrays.toString(arr);
Varargsvoid method(int... nums)
Enumenum Name { A, B, C }
Enum w/ fieldsenum E { A(1); int v; E(int v){this.v=v;} }
Section M

Self-Assessment Checkpoint

ConceptTool / PracticeOutputReady to Earn?
Loop Types (for, while, do-while)Java compiler + IDEMenu-driven programs, counters✅ Yes — foundation for all Java jobs
1D ArraysJava + Arrays classStudentMarksAnalyzer.java✅ Yes — build data processors
2D ArraysJava nested loopsMatrixMultiplier.java✅ Yes — matrix operations
java.util.Arrayssort, search, fill, copyNiftyPriceArrayProcessor.java✅ Yes — use in every project
VarargsJava method signaturesFlexible utility methods✅ Yes — API design skill
Enumerationsenum, EnumSet, EnumMapDayOfWeekEnum.java✅ Yes — type-safe design
Kadane's AlgorithmLeetCode #53O(n) max subarray solution✅ Yes — interview essential
Minimum Viable Earning Setup after this chapter: A GitHub profile with 4 Java programs (StockAnalyzer, MatrixMultiplier, DayOfWeekEnum, NiftyProcessor) + 50 solved LeetCode problems on arrays/loops + a Topmate/Unacademy profile offering DSA tutoring = ₹5,000–₹20,000/month while still in college.

✅ Unit 5 complete. MCQs: 30. Ready for Unit 6!

[QR: Link to EduArtha video tutorial — Java Loops, Arrays & Enums]