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)
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.
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.
Learning Outcomes — Bloom's Taxonomy Mapped
| Bloom's Level | Learning Outcome |
|---|---|
| 🔵 Remember | List the syntax of for, while, do-while loops and state rules for array declaration in Java |
| 🔵 Remember | Define enumeration, ordinal(), values(), and name() methods with correct signatures |
| 🔵 Understand | Explain the difference between for, enhanced for-each, while, and do-while loops with flowchart reasoning |
| 🔵 Understand | Describe how 1D and 2D arrays are stored in memory and why ArrayIndexOutOfBoundsException occurs |
| 🟢 Apply | Write a Java program using nested for loops to multiply two matrices and display the result |
| 🟢 Apply | Use java.util.Arrays methods (sort, binarySearch, fill, copyOf) to process student marks data |
| 🟢 Analyze | Compare the performance of for vs enhanced for-each for array traversal and identify when each is optimal |
| 🟢 Analyze | Debug a given loop-based program containing off-by-one errors, infinite loops, and incorrect break placement |
| 🟠 Evaluate | Assess whether to use arrays, ArrayList, or enum for a given real-world scenario with justification |
| 🟠 Evaluate | Critique a Nifty stock price analysis program for correctness, efficiency, and code quality |
| 🟠 Create | Design and implement a complete student marks analyzer using arrays, loops, and the Arrays utility class |
| 🟠 Create | Build an enum-based menu-driven application with EnumSet and EnumMap for an Indian railway booking scenario |
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
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 10Example — 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
< 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); }
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);
| Feature | for loop | while loop |
|---|---|---|
| Best When | Count is known in advance | Count depends on a condition |
| Initialization | Inside the for statement | Before the loop |
| Use Case | Iterating arrays, counting | Reading input, waiting for events |
| Risk | Off-by-one errors | Infinite 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
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"); } }
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(); } } }
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
| Operation | Code | Notes |
|---|---|---|
| Access element | arr[i] | 0-indexed; O(1) time |
| Get length | arr.length | Property, not method (no parentheses) |
| Modify element | arr[i] = value | O(1) time |
| Find element | Loop through array | O(n) linear search |
| Out of bounds | arr[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 } }
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.
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()); } } }
| Enum Method | Returns | Example |
|---|---|---|
name() | The constant name as String | Day.MONDAY.name() → "MONDAY" |
ordinal() | The position (0-based) | Day.MONDAY.ordinal() → 0 |
values() | Array of all constants | Day.values() → Day[7] |
valueOf(String) | Enum constant from name | Day.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()); } } }
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); } }
Learn by Doing — 3-Tier Lab: Nifty Stock Price Analyzer
🟢 Tier 1 — GUIDED TASK: Basic Stock Price Array Processor
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
Your Mission:
Extend Tier 1 to include a 3-day moving average and trend detection (uptrend/downtrend).
Hints:
- 3-Day SMA: For each day
i(starting from index 2), calculate(prices[i-2] + prices[i-1] + prices[i]) / 3.0 - Trend Detection: If the SMA is increasing for 3+ consecutive days, print "📈 UPTREND detected." If decreasing for 3+ days, print "📉 DOWNTREND detected."
- Daily Change %: For each day, calculate
((prices[i] - prices[i-1]) / prices[i-1]) * 100and flag days with >2% change as "⚠️ High volatility" - Sort & Display: Use
Arrays.copyOf()to create a sorted copy (don't modify original), then display the sorted prices
🔴 Tier 3 — OPEN CHALLENGE: Multi-Stock Portfolio Tracker
The Brief:
Build a complete portfolio tracker that handles multiple stocks. Requirements:
- Create an
enum Sector { IT, BANKING, PHARMA, AUTO, FMCG }with properties - Use a 2D array:
double[][] portfolio— rows = stocks, columns = daily prices - Track at least 5 stocks (Infosys, HDFC, Sun Pharma, Tata Motors, HUL) over 10 days
- Calculate per-stock: max, min, average, total return %
- Calculate portfolio-level: best performer, worst performer, sector-wise average returns
- Display results as a formatted table using
System.out.printf() - 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.
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."
MCQ Assessment Bank — 30 Questions (Bloom's Mapped)
Remember / Identify (Q1–Q5)
Which loop in Java checks the condition AFTER executing the body?
- for
- while
- do-while
- enhanced for
What is the default value of elements in a newly created int array in Java?
- null
- -1
- 0
- undefined
Which keyword is used to define an enumeration in Java?
- enumerate
- Enum
- enum
- const
enum keyword is used. Enum (capital E) is the base class, not the keyword.What does arr.length return for int[] arr = {10, 20, 30, 40, 50};?
- 4
- 5
- 6
- Compilation error
length field returns the total number of elements in the array, not the last index.Which syntax correctly declares a varargs parameter?
int[] numsint... numsint* numsint nums...
int... nums — The three dots come after the type and before the variable name. This is Java's varargs syntax.Understand / Explain (Q6–Q10)
Why does an enhanced for-each loop NOT allow modification of array elements?
- It uses a read-only copy of each element
- Arrays are immutable in Java
- The JVM locks the array during iteration
- It only works with final arrays
What happens when you access arr[arr.length]?
- Returns the last element
- Returns 0
- Throws ArrayIndexOutOfBoundsException
- Returns null
arr.length - 1. Index arr.length is out of bounds and throws ArrayIndexOutOfBoundsException at runtime.What does ordinal() return for the FIRST constant defined in an enum?
- 1
- 0
- -1
- The constant's hash code
Why is while preferred over for when reading user input until a sentinel value?
- while loops are faster
- The number of iterations is unknown in advance
- for loops cannot read input
- while loops use less memory
In a 2D array int[][] m = new int[3][4];, what does m.length and m[0].length return?
- 4 and 3
- 3 and 4
- 12 and 4
- 3 and 3
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)
What is the output?for(int i=1; i<=5; i++) { if(i==3) continue; System.out.print(i+" "); }
- 1 2 3 4 5
- 1 2 4 5
- 1 2
- 3
continue statement skips the current iteration when i==3, so 3 is not printed.What is the output?int[] a = {10,20,30}; System.out.println(a);
- [10, 20, 30]
- 10 20 30
- Something like [I@1a2b3c4
- Compilation error
Arrays.toString(a) to print readable contents.After executing: int[] x = {5,3,8,1}; Arrays.sort(x); what is x[2]?
- 8
- 3
- 5
- 1
What is the output?int i=5; do { System.out.print(i+" "); i--; } while(i>5);
- No output
- 5
- 5 4 3 2 1
- Infinite loop
What does Arrays.fill(new int[4], 7) produce?
- {0, 0, 0, 0}
- {7, 7, 7, 7}
- {7, 0, 0, 0}
- Compilation error
Arrays.fill() fills all elements of the array with the specified value.Apply / Code Completion (Q16–Q20)
Complete the blank to iterate backwards: for(int i = arr.length-1; i ___ 0; i--)
- >
- >=
- <
- !=
i >= 0. Using i > 0 would skip the first element.Which method returns an array of all constants in an enum?
- constants()
- getAll()
- values()
- enumerate()
values() method for every enum, returning an array of all constants in declaration order.What happens if you call Arrays.binarySearch() on an unsorted array?
- It sorts first, then searches
- Returns -1
- Result is undefined (unpredictable)
- Throws an exception
Which is valid for the enhanced for loop?
for (int x : 5)for (int x : arr)for (arr : int x)for (int x in arr)
for (Type variable : array/collection). Java uses : not in.Given void foo(String label, int... nums), which call is INVALID?
foo("test", 1, 2, 3)foo("test")foo("test", new int[]{1,2})foo(1, 2, "test")
Analyze / Compare (Q21–Q25)
Which loop type is most suitable for reading lines from a file until EOF?
- for loop
- do-while loop
- while loop
- enhanced for loop
scanner.hasNextLine() naturally handles this.Why might you prefer int[] over ArrayList<Integer> in a performance-critical loop?
- Arrays support generics
- Arrays avoid autoboxing overhead and have better cache locality
- ArrayList doesn't support iteration
- Arrays can grow dynamically
What is the bug?for(int i=0; i<10; i++) { if(i%2==0) continue; System.out.print(i); } // Intent: print even numbers
- Prints odd numbers instead of even
- Infinite loop
- Compilation error
- Prints nothing
if(i%2 != 0) continue; or remove continue and use an if block.In which scenario is an enum clearly better than static final int constants?
- When you need to store large numbers
- When you need type safety and want to prevent invalid values
- When you need dynamic values at runtime
- When memory is extremely limited
static final int, any integer value can be passed, but with enums, only valid constants are accepted by the compiler.What is the time complexity of finding the maximum element in an unsorted array of n elements?
- O(1)
- O(log n)
- O(n)
- O(n²)
Evaluate / Create (Q26–Q30)
Which approach is MOST efficient to find if a value exists in a sorted array of 1 million elements?
- Linear search with for loop
Arrays.binarySearch()- Enhanced for-each loop
- Converting to ArrayList and using
.contains()
A student writes: enum Color { RED, GREEN, BLUE; public Color() {} }. What happens?
- Compiles and runs fine
- Compilation error — enum constructors cannot be public
- Runtime exception
- Prints RED GREEN BLUE
Which design pattern is BEST implemented using a single-constant enum?
- Factory
- Observer
- Singleton
- Strategy
enum Singleton { INSTANCE; } is the recommended Singleton implementation (Joshua Bloch, Effective Java). It's thread-safe, serialization-safe, and reflection-proof.To store daily temperatures for 12 months × 30 days, the best structure is:
int[] temps = new int[360];int[][] temps = new int[12][30];ArrayList<Integer> temps;int temps;
temps[month][day] intuitive and efficient.Kadane's Algorithm for Maximum Subarray has which complexity?
- O(n²) time, O(n) space
- O(n log n) time, O(1) space
- O(n) time, O(1) space
- O(n) time, O(n) space
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.
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.
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 statisticsMatrixMultiplier.java— 2D array matrix multiplicationNiftyPriceArrayProcessor.java— Stock analysis with SMADayOfWeekEnum.java— Enum with properties and methods
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.
| Detail | Info |
|---|---|
| Tools Used Daily | Java 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 Hiring | Amazon, Flipkart, Google, Microsoft, Paytm, Razorpay, PhonePe, Zerodha, Atlassian, Goldman Sachs |
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
| Platform | Best For | Typical Rate |
|---|---|---|
| Topmate | 1-on-1 DSA mentoring sessions | ₹300–₹1,000/session |
| Unacademy | Teaching programming to large audience | ₹5,000–₹20,000/month |
| YouTube | Tutorial videos on Java/DSA | ₹2,000–₹50,000/month (after growth) |
| Internshala | Java development internships | ₹5,000–₹15,000/month |
| Fiverr | Small 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)
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)
Quick Reference — Syntax Cheat Sheet
| Concept | Syntax |
|---|---|
| for loop | for (int i = 0; i < n; i++) { } |
| for-each | for (int x : arr) { } |
| while | while (condition) { } |
| do-while | do { } while (condition); |
| 1D Array | int[] arr = new int[n]; or {1,2,3} |
| 2D Array | int[][] m = new int[r][c]; |
| Sort | Arrays.sort(arr); |
| Search | Arrays.binarySearch(sortedArr, key); |
Arrays.toString(arr); | |
| Varargs | void method(int... nums) |
| Enum | enum Name { A, B, C } |
| Enum w/ fields | enum E { A(1); int v; E(int v){this.v=v;} } |
Self-Assessment Checkpoint
| Concept | Tool / Practice | Output | Ready to Earn? |
|---|---|---|---|
| Loop Types (for, while, do-while) | Java compiler + IDE | Menu-driven programs, counters | ✅ Yes — foundation for all Java jobs |
| 1D Arrays | Java + Arrays class | StudentMarksAnalyzer.java | ✅ Yes — build data processors |
| 2D Arrays | Java nested loops | MatrixMultiplier.java | ✅ Yes — matrix operations |
| java.util.Arrays | sort, search, fill, copy | NiftyPriceArrayProcessor.java | ✅ Yes — use in every project |
| Varargs | Java method signatures | Flexible utility methods | ✅ Yes — API design skill |
| Enumerations | enum, EnumSet, EnumMap | DayOfWeekEnum.java | ✅ Yes — type-safe design |
| Kadane's Algorithm | LeetCode #53 | O(n) max subarray solution | ✅ Yes — interview essential |
✅ Unit 5 complete. MCQs: 30. Ready for Unit 6!
[QR: Link to EduArtha video tutorial — Java Loops, Arrays & Enums]