2. Java Control Flow, Loops, Arrays & Methods
Chapters 6-9: if/else, switch Expressions, for/while/do-while loops, 1D & 2D Arrays, Methods, Overloading & varargs
Module 1: Control Flow & Modern Switch Expressions
Directing program execution paths using conditional branching and value-producing switch expressions.
🇬🇧 English Definition
Control Flow determines statement execution order. Modern Java switch expressions (Java 14+) produce values directly using arrow syntax (->) without fall-through break statements.
🇮🇳 Hinglish Definition
Control flow branching condition check karta hai. Modern switch expression -> arrow syntax se direct value return karta hai.
Core Concepts & Rules
- if-else & else-if: Sequential boolean condition evaluation.
- Modern Switch Expression: String type = switch(day) { case 6,7 -> 'Weekend'; default -> 'Weekday'; };
🔍 Line-by-Line Code Breakdown
- Line 2: Set int day = 6.
- Line 3-6: Modern switch expression returns 'Weekend' directly using arrow syntax without break statements.
🎯 Interview Focus & Questions
- Q: Advantage of modern switch expression?
A: Prevents fall-through bugs, uses concise arrow (->) syntax, and yields values directly.
public class SwitchDemo {
public static void main(String[] args) {
int day = 6;
String type = switch(day) {
case 6, 7 -> "Weekend";
default -> "Weekday";
};
System.out.println("Day Type: " + type);
}
}
Module 2: Arrays, Utility Methods & Method Overloading
Managing fixed-size indexed arrays, 2D matrices, method overloading, and variable arguments (varargs).
🇬🇧 English Definition
Arrays store fixed-length elements of a single component type. Method Overloading allows multiple methods with identical names but distinct parameter signatures.
🇮🇳 Hinglish Definition
Array fixed length linear data store karta hai. Method Overloading me ek hi name ke methods alag parameter lists ke sath hote hain. Varargs (int... values) variable arguments handle karta hai.
Core Concepts & Rules
- 1D & 2D Arrays: int[] a = new int[3]; int[][] matrix = {{1,2},{3,4}};
- Arrays Utility: Arrays.sort(a) sorts arrays in ascending order; Arrays.toString(a) prints formatted arrays.
- Varargs: static int sum(int... values) accepts zero or more integer arguments.
🔍 Line-by-Line Code Breakdown
- Line 1-4: Varargs method sum(int... values) summing all passed arguments.
- Line 7: Arrays.sort(a) sorts array {5, 2, 9, 1} to {1, 2, 5, 9}.
🎯 Interview Focus & Questions
- Q: What is Varargs?
A: Varargs (type... name) allows a method to accept zero or more arguments of the specified type.
import java.util.Arrays;
public class ArrayMethodDemo {
static int sum(int... values) {
int total = 0;
for(int v : values) total += v;
return total;
}
public static void main(String[] args) {
int[] a = {5, 2, 9, 1};
Arrays.sort(a);
System.out.println("Sorted Array: " + Arrays.toString(a));
System.out.println("Varargs Sum: " + sum(1, 2, 3));
}
}