Programming in Java

Unit 4: Conditional Statements

From simple if-else decisions to complex switch expressions โ€” master every conditional construct in Java and build real-world decision engines.

โฑ๏ธ 4 hrs theory + 3 hrs lab  |  ๐Ÿ’ฐ Earning Potential: โ‚น5Kโ€“โ‚น15K/month  |  ๐Ÿ“ 30 MCQs (Bloom's Mapped)

๐Ÿ’ผ Jobs this unlocks: Java Developer (โ‚น4โ€“8 LPA)  |  Backend Engineer (โ‚น6โ€“12 LPA)  |  Automation Engineer (โ‚น5โ€“10 LPA)

Section A

Opening Hook โ€” The Code Behind Every IRCTC Ticket

๐Ÿš‚ How IRCTC Calculates Your Railway Fare in Milliseconds

Every time you book a train ticket on IRCTC, a fare engine fires up behind the scenes. It checks your travel class โ€” 1A (First AC), 2A (Second AC), 3A (Third AC), SL (Sleeper), or General โ€” and applies the right fare formula. A Delhiโ†’Mumbai journey costs โ‚น4,825 in 1A, โ‚น2,770 in 2A, โ‚น1,950 in 3A, โ‚น680 in SL, and โ‚น350 in General. Same route, same train, five completely different prices.

This isn't a complex AI model โ€” it's a switch-case statement. The system checks your selected class, jumps to the matching case, calculates the fare, and returns the result. No unnecessary comparisons, no wasted CPU cycles. Indian Railways processes 25+ million ticket requests on peak Tatkal days โ€” and at the heart of it all is conditional logic.

Every ticket you book triggers a switch-case. Every ATM withdrawal runs through an if-else chain. Every app login checks conditions. Conditional statements aren't just textbook theory โ€” they're the backbone of every piece of software you use daily.

๐Ÿ‡ฎ๐Ÿ‡ณ IRCTC๐Ÿ‡ฎ๐Ÿ‡ณ SBI ATM๐Ÿ‡ฎ๐Ÿ‡ณ Paytm๐Ÿ‡ฎ๐Ÿ‡ณ PhonePe๐Ÿ‡ฎ๐Ÿ‡ณ Razorpay๐Ÿ‡ฎ๐Ÿ‡ณ Zomato
Indian Railways runs 13,000+ trains daily and uses conditional logic in every subsystem โ€” from fare calculation to seat allocation, from waitlist priority to dynamic pricing on Tatkal tickets. The entire reservation system is built on billions of if-else and switch-case decisions executing every second.
Section B

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

Bloom's LevelLearning Outcome
๐Ÿ”ต RememberLO-1: List the syntax of if, if-else, switch, and switch expression statements in Java
๐Ÿ”ต RememberLO-2: Define the purpose of break, default, and yield keywords in switch constructs
๐Ÿ”ต UnderstandLO-3: Explain the difference between nested if-else and chained (else-if ladder) conditional structures
๐Ÿ”ต UnderstandLO-4: Describe how switch fall-through works and why it causes bugs in traditional switch statements
๐ŸŸข ApplyLO-5: Write a GradeCalculator program using nested if-else to assign letter grades from marks
๐ŸŸข ApplyLO-6: Implement an IRCTC Fare Calculator using both if-else chains and switch-case statements
๐ŸŸข ApplyLO-7: Build a SimpleATM menu-driven program using traditional switch-case with break
๐ŸŸ  AnalyzeLO-8: Compare traditional switch (with break) vs enhanced switch (Java 14+ arrow syntax) for readability and safety
๐ŸŸ  AnalyzeLO-9: Determine when to use if-else vs switch-case based on the type and number of conditions
๐ŸŸ  EvaluateLO-10: Evaluate switch fall-through traps in MCQ scenarios and predict output correctly
๐ŸŸ  EvaluateLO-11: Assess which conditional pattern best solves a given Indian industry problem scenario
๐Ÿ”ด CreateLO-12: Design a complete rule-based fare/discount calculator using multiple conditional constructs for a real-world Indian business scenario
Section C

Concept Explanation โ€” Conditional Statements from Scratch

1. The if Statement โ€” Your First Decision Maker

The if statement is the simplest form of decision-making in Java. It tests a boolean condition and executes a block of code only if the condition is true.

๐Ÿ“ Syntax: The if Statement

Structure:
Java
if (condition) {
    // code executes ONLY when condition is true
}
Plain English:

"If it's raining, take an umbrella." โ€” The umbrella action happens only when the rain condition is true. If it's sunny, you skip the umbrella entirely.

Rules:

โ€ข The condition inside () must evaluate to a boolean (true or false)
โ€ข Curly braces {} are optional for a single statement, but always use them for clarity
โ€ข The condition uses relational operators: ==, !=, <, >, <=, >=

Java
// Example: Check if a student passed
int marks = 72;

if (marks >= 40) {
    System.out.println("Congratulations! You passed the exam.");
}

if (marks >= 90) {
    System.out.println("Outstanding! You're a topper.");
}
Congratulations! You passed the exam.
Using = instead of == in conditions. if (marks = 40) is an ASSIGNMENT, not a comparison. Java will throw a compilation error because the result of marks = 40 is an int, not a boolean. Always use == for equality checks.

2. if-else and Nested if-else โ€” Two-Way and Multi-Way Decisions

The if-else Statement

When you need two paths โ€” one for true, one for false โ€” use if-else.

Java
int age = 16;

if (age >= 18) {
    System.out.println("Eligible to vote in Indian elections.");
} else {
    System.out.println("Not eligible to vote yet. Wait " + (18 - age) + " more years.");
}
Not eligible to vote yet. Wait 2 more years.

The else-if Ladder (Chained if-else)

When you have multiple conditions to check sequentially, use the else-if ladder. Java evaluates from top to bottom and executes the first matching block.

๐Ÿ† Full Program: GradeCalculator

Java
import java.util.Scanner;

public class GradeCalculator {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter your marks (0-100): ");
        int marks = sc.nextInt();

        char grade;
        String remark;

        if (marks < 0 || marks > 100) {
            System.out.println("Invalid marks! Must be 0-100.");
            return;
        } else if (marks >= 90) {
            grade = 'O';   // Outstanding
            remark = "Outstanding! Top of the class.";
        } else if (marks >= 80) {
            grade = 'A';
            remark = "Excellent performance!";
        } else if (marks >= 70) {
            grade = 'B';
            remark = "Good job, keep improving.";
        } else if (marks >= 60) {
            grade = 'C';
            remark = "Average. You can do better.";
        } else if (marks >= 40) {
            grade = 'D';
            remark = "Below average. Needs improvement.";
        } else {
            grade = 'F';
            remark = "Fail. Please re-appear.";
        }

        System.out.println("Grade: " + grade);
        System.out.println("Remark: " + remark);
    }
}
Enter your marks (0-100): 85 Grade: A Remark: Excellent performance!

Nested if-else โ€” Decision Inside a Decision

Sometimes you need to make a second decision within the first. This is nesting โ€” an if inside another if.

Java
// Nested if-else: Check eligibility for Indian Army
int age = 20;
double heightCm = 170.5;
boolean isCitizen = true;

if (isCitizen) {
    if (age >= 17 && age <= 21) {
        if (heightCm >= 157.5) {
            System.out.println("โœ… Eligible for Indian Army recruitment.");
        } else {
            System.out.println("โŒ Height requirement not met (min 157.5 cm).");
        }
    } else {
        System.out.println("โŒ Age must be between 17โ€“21 years.");
    }
} else {
    System.out.println("โŒ Must be an Indian citizen.");
}
โœ… Eligible for Indian Army recruitment.
Avoid deep nesting (more than 3 levels). Deeply nested if-else blocks are hard to read and debug. Refactor using early returns, guard clauses, or switch statements. If your indentation goes past 4 levels, something needs restructuring.

3. Traditional switch-case โ€” The Multi-Way Branch

Analogy: Think of switch-case like an IRCTC ticket counter. You walk up and say your class โ€” 1A, 2A, 3A, SL, or General. The counter clerk doesn't ask you 5 questions sequentially ("Is it 1A? No? Is it 2A? No?"). Instead, they hear your class once and jump straight to the right fare formula. That's exactly how switch works โ€” it evaluates the expression once and jumps to the matching case.

switch-case = IRCTC ticket counter โ€” check your class, apply the right fare formula. The clerk doesn't run through a checklist of all classes. They hear "2A" and immediately pull out the 2A fare chart. This is far more efficient than asking 5 sequential if-else questions.

๐Ÿ“ Syntax: Traditional switch-case

Java
switch (expression) {
    case value1:
        // code for value1
        break;
    case value2:
        // code for value2
        break;
    // ... more cases
    default:
        // code if no case matches
}
Rules:

โ€ข The expression must be byte, short, int, char, String, or an enum
โ€ข Each case value must be a compile-time constant (literal or final variable)
โ€ข break exits the switch block โ€” without it, execution falls through to the next case
โ€ข default is optional but recommended โ€” it handles unexpected values
โ€ข Duplicate case values cause a compilation error

๐Ÿ† Full Program: SimpleATM (switch)

Java
import java.util.Scanner;

public class SimpleATM {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double balance = 25000.00; // Initial balance in โ‚น

        System.out.println("โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—");
        System.out.println("โ•‘    SBI ATM โ€” Main Menu   โ•‘");
        System.out.println("โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ");
        System.out.println("โ•‘  1. Check Balance        โ•‘");
        System.out.println("โ•‘  2. Withdraw Cash        โ•‘");
        System.out.println("โ•‘  3. Deposit Cash         โ•‘");
        System.out.println("โ•‘  4. Mini Statement       โ•‘");
        System.out.println("โ•‘  5. Exit                 โ•‘");
        System.out.println("โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
        System.out.print("Enter your choice (1-5): ");

        int choice = sc.nextInt();

        switch (choice) {
            case 1:
                System.out.println("๐Ÿ’ฐ Your balance: โ‚น" + balance);
                break;

            case 2:
                System.out.print("Enter amount to withdraw: โ‚น");
                double withdraw = sc.nextDouble();
                if (withdraw > balance) {
                    System.out.println("โŒ Insufficient balance!");
                } else if (withdraw % 100 != 0) {
                    System.out.println("โŒ Amount must be multiple of โ‚น100");
                } else {
                    balance -= withdraw;
                    System.out.println("โœ… โ‚น" + withdraw + " withdrawn. New balance: โ‚น" + balance);
                }
                break;

            case 3:
                System.out.print("Enter amount to deposit: โ‚น");
                double deposit = sc.nextDouble();
                balance += deposit;
                System.out.println("โœ… โ‚น" + deposit + " deposited. New balance: โ‚น" + balance);
                break;

            case 4:
                System.out.println("๐Ÿ“„ Mini Statement:");
                System.out.println("   Current Balance: โ‚น" + balance);
                System.out.println("   Account Type: Savings");
                System.out.println("   Branch: SBI Main Branch");
                break;

            case 5:
                System.out.println("๐Ÿ™ Thank you for banking with SBI. Namaste!");
                break;

            default:
                System.out.println("โŒ Invalid choice! Please select 1-5.");
        }
    }
}
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ SBI ATM โ€” Main Menu โ•‘ โ• โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•ฃ โ•‘ 1. Check Balance โ•‘ โ•‘ 2. Withdraw Cash โ•‘ โ•‘ 3. Deposit Cash โ•‘ โ•‘ 4. Mini Statement โ•‘ โ•‘ 5. Exit โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• Enter your choice (1-5): 1 ๐Ÿ’ฐ Your balance: โ‚น25000.0

โš ๏ธ The Fall-Through Trap

If you forget break, Java doesn't stop at the matching case โ€” it "falls through" and executes ALL subsequent cases until it hits a break or the end of the switch block.

Java
// DANGEROUS: Missing break statements!
int day = 3;
switch (day) {
    case 1: System.out.println("Monday");
    case 2: System.out.println("Tuesday");
    case 3: System.out.println("Wednesday");  // โ† matches here
    case 4: System.out.println("Thursday");   // โ† falls through!
    case 5: System.out.println("Friday");     // โ† falls through!
    default: System.out.println("Weekend");   // โ† falls through!
}
Wednesday Thursday Friday Weekend
Forgetting break in switch is the #1 source of bugs in Java conditional code. When day is 3, you'd expect only "Wednesday" to print. Instead, ALL cases below it execute too. This is called "fall-through" and has caused countless production bugs. The enhanced switch (Java 14+) was designed specifically to eliminate this trap.

๐Ÿ† Full Program: DayOfWeekPrinter

Java
import java.util.Scanner;

public class DayOfWeekPrinter {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter day number (1-7): ");
        int day = sc.nextInt();

        String dayName;
        String type;

        switch (day) {
            case 1: dayName = "Monday";    type = "Weekday"; break;
            case 2: dayName = "Tuesday";   type = "Weekday"; break;
            case 3: dayName = "Wednesday"; type = "Weekday"; break;
            case 4: dayName = "Thursday";  type = "Weekday"; break;
            case 5: dayName = "Friday";    type = "Weekday"; break;
            case 6: dayName = "Saturday";  type = "Weekend"; break;
            case 7: dayName = "Sunday";    type = "Weekend"; break;
            default:
                System.out.println("Invalid day number!");
                return;
        }

        System.out.println("Day: " + dayName + " (" + type + ")");
    }
}
Enter day number (1-7): 5 Day: Friday (Weekday)

4. Enhanced Switch (Java 14+) โ€” Arrow Syntax & Switch Expressions

Java 14 introduced the enhanced switch with arrow syntax (->). This eliminates the need for break and prevents fall-through bugs entirely.

Arrow Syntax (No Fall-Through)

Java (14+)
int day = 3;

switch (day) {
    case 1 -> System.out.println("Monday");
    case 2 -> System.out.println("Tuesday");
    case 3 -> System.out.println("Wednesday");
    case 4 -> System.out.println("Thursday");
    case 5 -> System.out.println("Friday");
    case 6, 7 -> System.out.println("Weekend! ๐ŸŽ‰");
    default -> System.out.println("Invalid day");
}
Wednesday

Key differences from traditional switch:

FeatureTraditional switchEnhanced switch (14+)
Syntaxcase X: ... break;case X -> ...
Fall-throughYes (if break missing)No (impossible)
Multiple valuesStack cases (fall-through)case 6, 7 ->
Returns a value?No (it's a statement)Yes (switch expression)

Switch Expression with yield (Java 14+)

A switch expression returns a value. For multi-line blocks, use the yield keyword to specify what to return.

Java (14+)
int monthNum = 8;

String season = switch (monthNum) {
    case 12, 1, 2 -> "Winter โ„๏ธ";
    case 3, 4, 5 -> "Spring ๐ŸŒธ";
    case 6, 7, 8, 9 -> "Monsoon ๐ŸŒง๏ธ";
    case 10, 11 -> "Autumn ๐Ÿ‚";
    default -> "Invalid month";
};  // Note: semicolon at end โ€” it's an expression!

System.out.println("Season: " + season);
Season: Monsoon ๐ŸŒง๏ธ
Java (14+) โ€” yield in multi-line blocks
String travelClass = "2A";

double fare = switch (travelClass) {
    case "1A" -> {
        System.out.println("First AC โ€” Premium luxury");
        yield 4825.0;
    }
    case "2A" -> {
        System.out.println("Second AC โ€” Comfortable");
        yield 2770.0;
    }
    case "3A" -> {
        System.out.println("Third AC โ€” Budget AC");
        yield 1950.0;
    }
    case "SL" -> {
        System.out.println("Sleeper โ€” Most popular");
        yield 680.0;
    }
    case "GEN" -> {
        System.out.println("General โ€” Unreserved");
        yield 350.0;
    }
    default -> {
        System.out.println("Unknown class");
        yield 0.0;
    }
};

System.out.println("Fare: โ‚น" + fare);
Second AC โ€” Comfortable Fare: โ‚น2770.0

๐Ÿ† Full Program: IndianRailwayFareCalculator

Java
import java.util.Scanner;

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

        System.out.println("โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•—");
        System.out.println("โ•‘   ๐Ÿš‚ IRCTC Fare Calculator v2.0      โ•‘");
        System.out.println("โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");

        System.out.print("Enter base distance fare (โ‚น): ");
        double baseFare = sc.nextDouble();
        sc.nextLine(); // consume newline

        System.out.println("Travel Classes: 1A | 2A | 3A | SL | GEN");
        System.out.print("Enter your class: ");
        String travelClass = sc.nextLine().toUpperCase().trim();

        System.out.print("Tatkal booking? (yes/no): ");
        String tatkal = sc.nextLine().toLowerCase().trim();

        System.out.print("Senior citizen? (yes/no): ");
        String senior = sc.nextLine().toLowerCase().trim();

        double multiplier;
        String className;

        // Switch on travel class to set multiplier
        switch (travelClass) {
            case "1A":
                multiplier = 6.0;
                className = "First AC";
                break;
            case "2A":
                multiplier = 3.5;
                className = "Second AC";
                break;
            case "3A":
                multiplier = 2.5;
                className = "Third AC";
                break;
            case "SL":
                multiplier = 1.0;
                className = "Sleeper";
                break;
            case "GEN":
                multiplier = 0.5;
                className = "General";
                break;
            default:
                System.out.println("โŒ Invalid travel class!");
                return;
        }

        double totalFare = baseFare * multiplier;

        // Apply Tatkal surcharge using if-else
        if (tatkal.equals("yes")) {
            if (travelClass.equals("1A") || travelClass.equals("2A")) {
                totalFare += 400; // AC Tatkal charge
            } else if (travelClass.equals("3A")) {
                totalFare += 300;
            } else if (travelClass.equals("SL")) {
                totalFare += 200;
            }
            // GEN has no Tatkal
        }

        // Apply senior citizen discount using if
        if (senior.equals("yes")) {
            totalFare *= 0.6; // 40% discount
            System.out.println("๐Ÿง“ Senior citizen discount (40%) applied!");
        }

        System.out.println("\nโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
        System.out.println("๐ŸŽซ BOOKING SUMMARY");
        System.out.println("   Class     : " + className);
        System.out.println("   Base Fare : โ‚น" + baseFare);
        System.out.println("   Multiplier: " + multiplier + "x");
        System.out.println("   Tatkal    : " + (tatkal.equals("yes") ? "Yes" : "No"));
        System.out.println("   Senior    : " + (senior.equals("yes") ? "Yes" : "No"));
        System.out.printf("   TOTAL FARE: โ‚น%.2f%n", totalFare);
        System.out.println("โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•");
    }
}
โ•”โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•— โ•‘ ๐Ÿš‚ IRCTC Fare Calculator v2.0 โ•‘ โ•šโ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• Enter base distance fare (โ‚น): 800 Travel Classes: 1A | 2A | 3A | SL | GEN Enter your class: 2A Tatkal booking? (yes/no): yes Senior citizen? (yes/no): no โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ• ๐ŸŽซ BOOKING SUMMARY Class : Second AC Base Fare : โ‚น800.0 Multiplier: 3.5x Tatkal : Yes Senior : No TOTAL FARE: โ‚น3200.00 โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•โ•

5. Conditional Logic Design Patterns

Nested if-else vs Chained if-else โ€” When to Use What?

AspectNested if-elseChained if-else (else-if ladder)
Structureif inside if โ€” checks sub-conditionsSequential top-to-bottom checks
Use WhenConditions depend on each other (hierarchical)Conditions are independent / mutually exclusive
ExampleCheck citizenship โ†’ then age โ†’ then heightCheck marks: โ‰ฅ90? โ‰ฅ80? โ‰ฅ70? โ‰ฅ60?
ReadabilityCan get messy beyond 3 levelsCleaner for long condition lists
PerformanceSkips irrelevant branches earlyChecks sequentially until match
Indian Analogy๐Ÿง ATM: Insert card โ†’ Enter PIN โ†’ Select service๐Ÿฝ๏ธ Menu: Veg? Non-Veg? Jain? Vegan?

if-else vs switch-case โ€” Decision Guide

Choose if-else whenโ€ฆChoose switch whenโ€ฆ
Conditions involve ranges (>, <, >=)Comparing one variable against exact values
Complex boolean expressions (&&, ||)Variable is int, char, String, or enum
Few conditions (2-3)Many exact-match conditions (4+)
Example: marks โ‰ฅ 90, age < 18Example: day == 1, month == "JAN"
Interview wisdom: "Use if-else for ranges and complex logic; use switch for discrete values and menu-driven programs." This one-liner answer has helped countless Indian candidates clear TCS, Wipro, and Infosys technical rounds.
Section D

Learn by Doing โ€” 3-Tier Lab: IRCTC Fare Calculator

๐ŸŸข Tier 1 โ€” GUIDED: Basic Fare Calculator (if-else)

โฑ๏ธ 30โ€“45 minutesBeginnerStep-by-step instructions

Objective:

Build a simple fare calculator that takes distance and travel class as input and outputs the fare using if-else.

Step 1: Create the file

Create BasicFareCalculator.java in your IDE.

Step 2: Write the code

Java
import java.util.Scanner;

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

        System.out.print("Enter distance (km): ");
        int distance = sc.nextInt();
        sc.nextLine();

        System.out.print("Enter class (1A/2A/3A/SL/GEN): ");
        String cls = sc.nextLine().toUpperCase();

        double ratePerKm;

        if (cls.equals("1A")) {
            ratePerKm = 4.25;
        } else if (cls.equals("2A")) {
            ratePerKm = 2.50;
        } else if (cls.equals("3A")) {
            ratePerKm = 1.75;
        } else if (cls.equals("SL")) {
            ratePerKm = 0.80;
        } else if (cls.equals("GEN")) {
            ratePerKm = 0.35;
        } else {
            System.out.println("Invalid class!");
            return;
        }

        double fare = distance * ratePerKm;
        System.out.printf("Fare for %d km in %s: โ‚น%.2f%n", distance, cls, fare);
    }
}

Step 3: Compile & Run

Terminal
javac BasicFareCalculator.java
java BasicFareCalculator

Step 4: Test with these inputs

DistanceClassExpected Fare
1400 km1Aโ‚น5950.00
1400 kmSLโ‚น1120.00
500 kmGENโ‚น175.00

๐ŸŸก Tier 2 โ€” SEMI-GUIDED: Fare Calculator with switch + Tatkal

โฑ๏ธ 45โ€“60 minutesIntermediateHints provided

Your Mission:

Convert the Tier 1 if-else calculator to use switch-case. Add Tatkal surcharge and senior citizen discount logic.

Hints:

  1. Use switch (cls) instead of the if-else chain for the rate lookup
  2. Add a boolean isTatkal โ€” if true, add 10% surcharge for AC classes, 15% for SL
  3. Add a boolean isSenior โ€” if true, apply 40% discount on final fare
  4. Print a detailed receipt with all line items
  5. Handle invalid class in the default case
Stretch Goal: Add a "Superfast" surcharge of โ‚น75 if the train is a Rajdhani/Shatabdi. Use another switch or if condition for train type.

๐Ÿ”ด Tier 3 โ€” OPEN CHALLENGE: Complete IRCTC Booking System

โฑ๏ธ 90โ€“120 minutesAdvancedNo hand-holding

The Brief:

Build a complete terminal-based IRCTC booking system that supports:

  1. Multiple routes: Delhiโ†’Mumbai, Mumbaiโ†’Chennai, Kolkataโ†’Delhi (each with different base fares)
  2. All 5 classes: 1A, 2A, 3A, SL, GEN with different multipliers
  3. Tatkal surcharge: Different for AC and Non-AC classes
  4. Senior citizen discount: 40% for male seniors (60+), 50% for female seniors (58+)
  5. GST: 5% on total fare
  6. Meal booking: Optional โ€” โ‚น150 for Veg, โ‚น200 for Non-Veg (use switch)
  7. Receipt: Print a formatted booking receipt with PNR (random 10-digit number)

Deliverable: A single Java file named IRCTCBookingSystem.java with clean code and proper comments.

This project is portfolio-worthy. Add it to your GitHub, mention it in your resume under "Projects," and be ready to explain the conditional logic in interviews. Companies like TCS and Infosys love seeing real-world inspired projects.
Section E

Problem Set โ€” Practice Questions

๐Ÿ”ค Syntax Questions (5)

S1. Write the syntax of a traditional switch-case statement with break and default.

S2. Write the syntax of an enhanced switch expression (Java 14+) with arrow syntax that returns a value.

S3. Write a nested if-else structure that checks three conditions: citizenship, age range, and qualification.

S4. What is the difference between yield and return in a switch expression? Write a code snippet demonstrating yield.

S5. Write a switch-case that groups multiple case labels together (e.g., Mondayโ€“Friday as "Weekday") using (a) traditional fall-through and (b) enhanced comma-separated syntax.

๐Ÿ’ป Programming Questions (8)

P1. Write a Java program that takes a month number (1-12) and prints the number of days in that month (handle leap year for February using nested if).

P2. Create an IncomeTaxCalculator that takes annual income and calculates tax using the Indian tax slabs: 0-2.5L โ†’ 0%, 2.5-5L โ†’ 5%, 5-10L โ†’ 20%, 10L+ โ†’ 30%.

P3. Build a VowelConsonantChecker using switch-case that takes a character and prints whether it's a vowel, consonant, digit, or special character.

P4. Write a BMICalculator that takes weight (kg) and height (m), calculates BMI, and classifies it as Underweight/Normal/Overweight/Obese using if-else.

P5. Create a SimpleCalculator that takes two numbers and an operator (+, -, *, /, %) using switch-case and performs the calculation with division-by-zero handling.

P6. Write an ElectricityBillCalculator using Indian tariff slabs: 0-100 units โ†’ โ‚น1.5/unit, 101-300 โ†’ โ‚น3.5/unit, 301-500 โ†’ โ‚น5.5/unit, 500+ โ†’ โ‚น8/unit. Use if-else chain.

P7. Build a TrafficLightSimulator using enhanced switch (Java 14+) that takes a color ("RED", "YELLOW", "GREEN") and prints the action with duration in seconds.

P8. Create an AgeGroupClassifier that takes age and classifies into: Infant (0-1), Toddler (2-4), Child (5-12), Teenager (13-19), Adult (20-59), Senior (60+). Handle negative ages as invalid.

๐Ÿญ Industry-Level Questions (3)

I1. Paytm Cashback Engine: Design a cashback calculator where: UPI payments โ‰ฅโ‚น500 get 2% cashback, Credit card payments get 1%, Paytm Wallet gets 3%. Apply a max cashback cap of โ‚น100. Use a combination of switch (payment method) and if-else (amount threshold).

I2. Swiggy Delivery Fee Calculator: Build a program where delivery fee depends on: distance (<3 km โ†’ Free, 3-7 km โ†’ โ‚น25, 7-12 km โ†’ โ‚น50, 12+ km โ†’ โ‚น75), time of day (peak hours 12-2 PM and 7-10 PM add โ‚น15 surge), and membership (Swiggy One members get free delivery under 10 km).

I3. CRED Score Evaluator: Write a program that takes a credit score (300-900) and determines loan eligibility: 750+ โ†’ All loans approved at best rates, 650-749 โ†’ Personal loan approved with higher interest, 550-649 โ†’ Only secured loans, Below 550 โ†’ No loans approved. Use nested if-else.

๐ŸŽฏ Interview Questions (3)

IV1. What is the output of this code? (TCS/Wipro favourite):

Java
int x = 2;
switch(x) {
    case 1: System.out.print("A");
    case 2: System.out.print("B");
    case 3: System.out.print("C");
    default: System.out.print("D");
}

IV2. Can you use long, float, or boolean in a switch expression? Explain why or why not.

IV3. Rewrite this nested if-else as a switch expression (Java 14+):

Java
String status;
if (code == 200) status = "OK";
else if (code == 404) status = "Not Found";
else if (code == 500) status = "Server Error";
else status = "Unknown";
Section F

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

Remember / Identify (Q1โ€“Q5)

Q1

Which keyword is used to exit a switch-case block in traditional Java switch?

  1. exit
  2. stop
  3. break
  4. continue
Remember
โœ… Answer: (C) break โ€” The break keyword terminates the switch block. Without it, execution falls through to subsequent cases.
Q2

Which of these data types CANNOT be used in a Java switch expression?

  1. int
  2. String
  3. float
  4. char
Remember
โœ… Answer: (C) float โ€” switch supports byte, short, int, char, String, and enum. Floating-point types (float, double) and long are NOT allowed because exact equality comparison on floats is unreliable.
Q3

The default case in a switch statement is:

  1. Mandatory in every switch
  2. Always placed at the end
  3. Optional and can be placed anywhere
  4. Executed before all other cases
Remember
โœ… Answer: (C) โ€” The default case is optional and can appear anywhere in the switch block (though convention places it last). It executes when no case matches.
Q4

In Java 14+, which keyword is used to return a value from a multi-line switch expression block?

  1. return
  2. yield
  3. break
  4. output
Remember
โœ… Answer: (B) yield โ€” In switch expressions with multi-line blocks ({ }), yield returns the value. return would exit the entire method, not just the switch.
Q5

What operator does enhanced switch (Java 14+) use instead of case value:?

  1. case value =>
  2. case value ->
  3. case value ::
  4. case value >>>
Remember
โœ… Answer: (B) case value -> โ€” The arrow syntax (->) replaces the colon, eliminates fall-through, and removes the need for break statements.

Understand / Explain (Q6โ€“Q10)

Q6

What is "fall-through" in a switch statement?

  1. The switch block fails to compile
  2. Execution continues to subsequent cases after a match when break is missing
  3. The default case overrides all other cases
  4. The switch expression returns null
Understand
โœ… Answer: (B) โ€” Fall-through occurs when break is missing. After matching a case, Java continues executing ALL subsequent case blocks until it encounters a break or reaches the end of the switch.
Q7

Why can't long be used in a switch statement?

  1. long values are too large for the JVM to index efficiently in a switch lookup table
  2. long is a floating-point type
  3. long cannot be compared with ==
  4. long was deprecated in Java 14
Understand
โœ… Answer: (A) โ€” Switch internally uses lookup tables or jump tables optimized for 32-bit integers. long is 64-bit and would break these optimizations. Use if-else for long comparisons.
Q8

What is the advantage of using an else-if ladder over nested if-else for grade calculation?

  1. Else-if ladders run faster
  2. Else-if ladders are flatter and more readable for mutually exclusive conditions
  3. Nested if-else cannot handle multiple conditions
  4. Else-if ladders don't need boolean expressions
Understand
โœ… Answer: (B) โ€” When conditions are mutually exclusive (only one can be true), else-if ladders keep code flat and readable. Nested if-else creates deep indentation and is harder to maintain.
Q9

In Java, what happens if all conditions in an if-else-if ladder are false and there is no else block?

  1. Compilation error
  2. Runtime exception
  3. Nothing executes โ€” the program continues past the ladder
  4. The first if block executes by default
Understand
โœ… Answer: (C) โ€” If no condition is true and there's no else, Java simply skips the entire ladder and continues with the next statement. No error occurs.
Q10

Why does Java 14+ enhanced switch prevent fall-through?

  1. It uses arrow syntax (->) which executes only the matched arm
  2. It automatically adds break statements
  3. It doesn't support multiple cases
  4. It only works with String types
Understand
โœ… Answer: (A) โ€” The arrow syntax (->) makes each arm a self-contained expression. Only the matched arm executes, then control exits the switch. No fall-through is possible.

Apply / Implement (Q11โ€“Q15)

Q11

What is the output?

int x = 5;
if (x > 3)
    if (x > 7)
        System.out.print("A");
    else
        System.out.print("B");
else
    System.out.print("C");
  1. A
  2. B
  3. C
  4. Compilation error
Apply
โœ… Answer: (B) โ€” x=5 passes x > 3 (true), enters inner if. x > 7 is false, so the inner else prints "B". The "dangling else" attaches to the nearest unmatched if.
Q12

What is the output? (Fall-through trap!)

int val = 1;
switch(val) {
    case 1: System.out.print("One");
    case 2: System.out.print("Two");
    case 3: System.out.print("Three");
    default: System.out.print("Default");
}
  1. One
  2. OneTwo
  3. OneTwoThreeDefault
  4. Compilation error
ApplyFall-through Trap
โœ… Answer: (C) OneTwoThreeDefault โ€” No break statements, so after matching case 1, execution falls through ALL remaining cases including default.
Q13

What is the output?

char ch = 'B';
switch(ch) {
    case 'A': case 'E': case 'I':
        System.out.print("Vowel"); break;
    default:
        System.out.print("Consonant");
}
  1. Vowel
  2. Consonant
  3. VowelConsonant
  4. Compilation error
Apply
โœ… Answer: (B) Consonant โ€” 'B' doesn't match 'A', 'E', or 'I', so default executes. The grouped cases (A, E, I) use intentional fall-through to share the same code block.
Q14

What is the output?

int marks = 75;
if (marks >= 90) System.out.print("A");
else if (marks >= 80) System.out.print("B");
else if (marks >= 70) System.out.print("C");
else if (marks >= 60) System.out.print("D");
else System.out.print("F");
  1. A
  2. B
  3. C
  4. CD
Apply
โœ… Answer: (C) โ€” marks=75 fails โ‰ฅ90 and โ‰ฅ80, but passes โ‰ฅ70. Since it's an else-if ladder, only the first matching block executes. "C" is printed, and โ‰ฅ60 is never checked.
Q15

What is the output of this enhanced switch? (Java 14+)

String result = switch(3) {
    case 1 -> "One";
    case 2, 3 -> "Two or Three";
    default -> "Other";
};
System.out.println(result);
  1. One
  2. Two or Three
  3. Other
  4. Compilation error
Apply
โœ… Answer: (B) Two or Three โ€” Case 2 and 3 are grouped with comma syntax. Value 3 matches this arm, returning "Two or Three".

Analyze / Compare (Q16โ€“Q20)

Q16

Which approach is more appropriate for checking if a number is within a range (e.g., 1โ€“100)?

  1. switch-case
  2. if-else
  3. Either works equally well
  4. Neither โ€” use a loop
Analyze
โœ… Answer: (B) if-else โ€” Range checks require relational operators (<, >=) which switch does not support. Switch requires exact constant values, making it unsuitable for ranges.
Q17

What is the output? (Fall-through with break in the middle)

int n = 2;
switch(n) {
    case 1: System.out.print("A");
    case 2: System.out.print("B");
    case 3: System.out.print("C"); break;
    case 4: System.out.print("D");
    default: System.out.print("E");
}
  1. B
  2. BC
  3. BCD
  4. BCDE
AnalyzeFall-through Trap
โœ… Answer: (B) BC โ€” n=2 matches case 2, prints "B". Falls through to case 3, prints "C". Then hits break which stops execution. Case 4 and default are NOT reached.
Q18

Why is enhanced switch (Java 14+) considered safer than traditional switch?

  1. It runs faster
  2. It eliminates fall-through bugs by design
  3. It supports more data types
  4. It allows nested switch expressions
Analyze
โœ… Answer: (B) โ€” The arrow syntax (->) makes fall-through impossible. Each arm is isolated, so missing a break can never cause bugs. This was the primary motivation for the Java 14 enhancement.
Q19

What is the output?

int a = 10, b = 20;
if (a > b)
    System.out.print("X");
    System.out.print("Y");
  1. XY
  2. X
  3. Y
  4. Nothing
AnalyzeTricky Indentation
โœ… Answer: (C) Y โ€” Without curly braces, only the FIRST statement belongs to the if. System.out.print("Y") is NOT inside the if โ€” it always executes regardless of the condition. This is why you should always use braces!
Q20

In an IRCTC fare system, if you need to handle 5 discrete travel classes (1A, 2A, 3A, SL, GEN), which is the best construct?

  1. Nested if-else
  2. switch-case on String
  3. Ternary operator chain
  4. while loop
Analyze
โœ… Answer: (B) โ€” Discrete exact-match values on a String are perfect for switch. It's cleaner, more readable, and potentially faster than an if-else chain for 5+ cases.

Evaluate / Judge (Q21โ€“Q25)

Q21

A junior developer wrote this. What's wrong?

switch(grade) {
    case "A": System.out.println("Excellent");
    case "B": System.out.println("Good");
    case "A": System.out.println("Outstanding");
}
  1. Missing break statements only
  2. Duplicate case labels cause compilation error
  3. String can't be used in switch
  4. Missing default case
EvaluateFall-through Trap
โœ… Answer: (B) โ€” Duplicate case labels ("A" appears twice) cause a compilation error in Java. Each case value must be unique. The missing breaks and default are also issues, but the duplicate label stops compilation entirely.
Q22

Which code correctly handles the "dangling else" problem?

  1. Using braces {} to explicitly define scope
  2. Adding comments to clarify intent
  3. Using switch instead of if
  4. Adding blank lines for readability
Evaluate
โœ… Answer: (A) โ€” The dangling else problem occurs when an else could attach to multiple if statements. Braces explicitly define which if the else belongs to, eliminating ambiguity.
Q23

Evaluate: "switch is always faster than if-else." Is this true?

  1. True โ€” switch uses jump tables internally
  2. False โ€” for 2-3 conditions, if-else can be equally fast or faster
  3. True โ€” switch skips all non-matching cases
  4. False โ€” switch is always slower
Evaluate
โœ… Answer: (B) โ€” For small numbers of conditions (2-3), if-else may be equally efficient. Switch's jump table advantage shows with many cases (5+). The JIT compiler optimizes both in practice.
Q24

What is the output? (Tricky default placement)

int x = 5;
switch(x) {
    default: System.out.print("D");
    case 1: System.out.print("A"); break;
    case 2: System.out.print("B");
}
  1. D
  2. DA
  3. DAB
  4. A
EvaluateFall-through Trap
โœ… Answer: (B) DA โ€” x=5 doesn't match case 1 or 2, so default executes printing "D". No break in default, so falls through to case 1, printing "A". Then break stops execution.
Q25

Which code is better practice for a menu-driven program?

// Option A: if-else
if(choice==1) {...}
else if(choice==2) {...}
else if(choice==3) {...}

// Option B: switch
switch(choice) {
  case 1: ...break;
  case 2: ...break;
  case 3: ...break;
}
  1. Option A โ€” if-else is always better
  2. Option B โ€” switch is cleaner, more readable, and optimized for exact-match values
  3. Both are identical in every way
  4. Neither โ€” use arrays instead
Evaluate
โœ… Answer: (B) โ€” For menu-driven programs with discrete integer choices, switch is the standard approach. It's more readable, the compiler can optimize it with jump tables, and the structure clearly maps choices to actions.

Create / Design (Q26โ€“Q30)

Q26

You need to build a discount calculator: 0-500 โ†’ 0%, 501-2000 โ†’ 5%, 2001-5000 โ†’ 10%, 5001+ โ†’ 15%. Which construct should you use?

  1. switch-case
  2. if-else ladder with range comparisons
  3. Nested switch
  4. Single if statement
Create
โœ… Answer: (B) โ€” Range-based conditions require relational operators (<=, >) which switch cannot handle. An if-else ladder with range checks is the correct and only approach.
Q27

To create a Java 14+ switch expression that maps HTTP status codes to messages and returns a String, which syntax is correct?

  1. String msg = switch(code) { case 200 -> "OK"; default -> "Unknown"; };
  2. switch(code) { case 200: return "OK"; }
  3. String msg = switch(code) { case 200: "OK"; default: "Unknown"; };
  4. switch(code) -> { case 200 => "OK"; }
Create
โœ… Answer: (A) โ€” Correct switch expression syntax: Type var = switch(expr) { case val -> result; default -> fallback; }; Note the semicolon at the end โ€” it's an expression/statement.
Q28

What is the output?

int x = 0;
switch(x) {
    case 0: System.out.print("Zero");
    default: System.out.print("Def"); break;
    case 1: System.out.print("One");
}
  1. Zero
  2. ZeroDef
  3. ZeroDefOne
  4. ZeroOne
CreateFall-through Trap
โœ… Answer: (B) ZeroDef โ€” x=0 matches case 0, prints "Zero". Falls through to default, prints "Def". Then break exits. Case 1 is NOT reached because of the break in default.
Q29

You're designing a Zomato-like app. For restaurant filtering, users select: "Veg", "Non-Veg", "Jain", "Vegan", or "Eggetarian". Which construct is most appropriate?

  1. Nested if-else
  2. switch on String
  3. Ternary operator
  4. for loop with conditions
Create
โœ… Answer: (B) โ€” Five discrete String values is a perfect use case for switch on String. Each food preference maps to a specific filter action. Clean, readable, and maintainable.
Q30

Which of the following will NOT compile?

  1. switch("hello") { case "hello" -> System.out.println("Hi"); }
  2. switch(10L) { case 10L -> System.out.println("Ten"); }
  3. switch('A') { case 'A' -> System.out.println("Alpha"); }
  4. switch(1) { case 1 -> System.out.println("One"); }
CreateCompilation Error
โœ… Answer: (B) โ€” long is not a valid switch expression type in Java. Switch supports byte, short, int, char, String, and enum โ€” but NOT long, float, double, or boolean.
Section G

Short Answer Questions (8)

SA-1: What is the difference between if-else and switch?

if-else evaluates boolean expressions and supports ranges, complex conditions, and any data type. It checks conditions sequentially from top to bottom.

switch compares a single expression against discrete constant values. It supports only byte, short, int, char, String, and enum. It uses an internal lookup/jump table for faster matching with many cases.

Key rule: Use if-else for ranges and complex logic; use switch for exact-value matching against a single variable.

SA-2: Explain "fall-through" in switch with an example.

Fall-through occurs when a break statement is missing after a case block. After the matched case executes, Java continues executing ALL subsequent cases until it hits a break or the end of the switch.

Java
int n = 1;
switch(n) {
    case 1: System.out.print("A"); // matches, prints A
    case 2: System.out.print("B"); // falls through, prints B
    case 3: System.out.print("C"); // falls through, prints C
}
// Output: ABC (not just A!)

SA-3: What data types are valid for a switch expression in Java?

Valid: byte, short, int, char, String (Java 7+), and enum types. Their wrapper classes (Byte, Short, Integer, Character) also work via auto-unboxing.

Invalid: long, float, double, boolean. These are not supported because switch uses jump tables optimized for 32-bit integers, and floating-point equality is unreliable.

SA-4: What is the "dangling else" problem?

When nested if statements don't use braces, it's ambiguous which if an else belongs to. Java resolves this by attaching else to the nearest unmatched if.

Java
if (x > 0)          // outer if
    if (x > 100)     // inner if
        print("Big");
    else             // belongs to inner if (nearest), NOT outer!
        print("Small");
// Solution: ALWAYS use braces {}

SA-5: Compare yield vs return in switch expressions.

yield: Returns a value from a switch expression block. Exits only the switch, not the method.

return: Exits the entire method and returns a value to the caller.

In a switch expression with multi-line blocks, you MUST use yield (not return) to specify the value.

SA-6: Why is break not needed in enhanced switch (Java 14+)?

Enhanced switch uses arrow syntax (->) which makes each case arm a self-contained unit. Only the matched arm executes, then control automatically exits the switch. Fall-through is structurally impossible, so break is unnecessary and not even allowed.

SA-7: What is the purpose of the default case?

The default case executes when none of the specified case values match the switch expression. It acts as a catch-all for unexpected values. While optional in statement switches, it is mandatory in switch expressions if the cases don't cover all possible values (to ensure the expression always returns a value).

SA-8: Can you write a switch with no cases, only a default?

Yes! This is valid Java:

Java
switch(x) {
    default: System.out.println("Always executes");
}

Though technically valid, it's pointless โ€” just use the statement directly without a switch. This might appear in tricky interview questions.

Section H

Long Answer Questions (3)

LA-1: Explain all types of conditional statements in Java with examples. Compare when to use each.

Answer should cover (10 marks):

  1. Simple if: Single-condition check. Example: checking if marks โ‰ฅ 40 to print "Pass".
  2. if-else: Two-way branching. Example: eligible/not eligible to vote based on age โ‰ฅ 18.
  3. else-if ladder: Multi-way sequential checking. Example: grade assignment (O, A, B, C, D, F) based on marks ranges.
  4. Nested if-else: Hierarchical conditions where sub-conditions depend on outer conditions. Example: Army eligibility checking citizenship โ†’ age โ†’ height.
  5. Traditional switch-case: Multi-way exact-value matching with break/default. Example: ATM menu (1=Balance, 2=Withdraw, etc.).
  6. Enhanced switch (Java 14+): Arrow syntax without fall-through, comma-grouped cases, switch expressions returning values with yield.

Comparison table: if-else supports ranges and complex boolean logic; switch supports exact values only but is cleaner for 4+ discrete cases. Enhanced switch eliminates fall-through bugs entirely.

LA-2: Write a complete Indian Railway Fare Calculator program using both if-else and switch-case. Explain your design decisions.

Answer should include (10 marks):

  1. Complete working Java program with Scanner input
  2. switch-case for travel class (1A/2A/3A/SL/GEN) โ†’ rate multiplier
  3. if-else for Tatkal surcharge (different for AC vs non-AC classes)
  4. if-else for senior citizen discount (40% off)
  5. Formatted receipt output with all line items
  6. Design decisions: Why switch for class? (discrete values). Why if-else for Tatkal? (conditional + requires knowing the class). Why not use all if-else? (switch is cleaner for 5 exact String values)

Refer to the IndianRailwayFareCalculator program in Section C for a complete implementation.

LA-3: Explain the evolution of switch in Java โ€” from traditional to enhanced switch expressions. Why did Java 14 introduce these changes?

Answer should cover (10 marks):

  1. Traditional switch (Java 1.0): Colon syntax, break required, fall-through by default, limited to int/char.
  2. Switch on String (Java 7): Added String support. Internally converts to hashCode() comparisons.
  3. Enhanced switch with arrows (Java 14): Arrow syntax (->), no fall-through, comma-separated case labels.
  4. Switch expressions (Java 14): Switch can now return a value. Use yield for multi-line blocks. Must be exhaustive (cover all possible values).
  5. Why these changes? (a) Eliminate the #1 source of switch bugs โ€” accidental fall-through. (b) Enable functional-style programming. (c) Prepare for pattern matching (Java 17+). (d) Make code more concise and readable.
  6. Code examples comparing old vs new syntax for the same problem.
Section I

Lab Programs

All lab exercises for this unit are integrated into Section D (Learn by Doing) as a 3-tier lab structure. The labs use the IRCTC Fare Calculator as the unifying project, progressively building complexity from basic if-else (Tier 1) through switch-case (Tier 2) to a complete booking system (Tier 3).

Recommended lab workflow: Complete Tier 1 in class (guided), attempt Tier 2 as homework (semi-guided), and submit Tier 3 as a mini-project (open challenge). Each tier builds on the previous one.
Section J

Industry Spotlight โ€” A Day in the Life

๐Ÿ‘ฉโ€๐Ÿ’ป Sneha Gupta, 26 โ€” Java Developer at TCS, Pune

Background: B.Tech in Computer Science from VIT Pune. No prior industry experience before joining TCS through campus placement. Trained in Java during TCS ILP (Initial Learning Program). Now works on a banking middleware project for a major Indian bank.

A Typical Day:

9:30 AM โ€” Morning standup with the team. Discuss yesterday's sprint progress. Review a Jira ticket for a new loan eligibility feature.

10:00 AM โ€” Write Java code for a loan approval engine. Uses nested if-else to check: credit score โ‰ฅ 750 โ†’ check income โ†’ check existing EMIs โ†’ approve/reject. "It's all conditional logic at the core."

11:30 AM โ€” Code review with senior developer. Refactors a massive if-else chain into a switch expression (Java 17) for cleaner code. "My lead said: if you're comparing the same variable against 5+ values, switch it."

1:00 PM โ€” Lunch break. Discusses upcoming Java certification (OCA) with colleagues.

2:00 PM โ€” Fixes a bug where a missing break in a switch caused incorrect transaction categorization. "Classic fall-through bug. One missing break caused lakhs of transactions to be miscategorized."

4:00 PM โ€” Writes JUnit test cases for the loan approval engine. Tests edge cases: exactly 750 credit score, negative income, zero EMIs.

5:30 PM โ€” Attends a tech talk on Java 21 pattern matching. "The new switch with pattern matching is going to change how we write conditional code."

DetailInfo
Tools Used DailyJava 17, Spring Boot, IntelliJ IDEA, Git, Jira, Postman, JUnit
Entry Salary (TCS)โ‚น3.6โ€“7 LPA (Digital/Ninja/Prime)
Mid-Level (3โ€“5 yrs)โ‚น8โ€“15 LPA
Senior (7+ yrs)โ‚น18โ€“30 LPA
Companies Hiring JavaTCS, Infosys, Wipro, HCL, Cognizant, Capgemini, JP Morgan, Goldman Sachs, Amazon, Flipkart
Section K

Earn With It โ€” Rule-Based Calculator Apps

๐Ÿ’ฐ Your Earning Path After This Unit

Portfolio Piece: "IRCTC Fare Calculator" and "Indian Tax Calculator" โ€” clean, well-commented Java programs on GitHub demonstrating mastery of if-else and switch-case.

Beginner Gig Ideas (โ‚น5Kโ€“โ‚น15K/month):

โ€ข Rule-based calculator apps for local businesses (pricing, discount, tax) โ€” โ‚น2,000โ€“โ‚น5,000/project

โ€ข Quiz/assessment apps with grading logic for coaching centres โ€” โ‚น3,000โ€“โ‚น8,000

โ€ข Menu-driven console applications for shop billing โ€” โ‚น2,000โ€“โ‚น5,000

โ€ข Freelance Java programming assignments for engineering students โ€” โ‚น500โ€“โ‚น2,000/assignment

PlatformBest ForTypical Rate
InternshalaJava internships & freelanceโ‚น2,000โ€“โ‚น8,000/project
FiverrJava programming tasks$10โ€“$50/gig
Chegg / Course HeroAnswering Java questionsโ‚น100โ€“โ‚น300/answer
GitHub PortfolioShowcasing projects for job applicationsIndirect โ€” leads to โ‚น4โ€“8 LPA job
WhatsApp/CollegeHelping batchmates with assignmentsโ‚น200โ€“โ‚น1,000/assignment
Build in public. Push every program you write to GitHub with clear README files. Recruiters at TCS, Infosys, and product companies check GitHub profiles. A profile with 20+ Java programs shows consistency and passion โ€” which is worth more than certifications alone.
Section L

Chapter Summary

๐Ÿง  Key Takeaways โ€” Unit 4: Conditional Statements

โœ… if statement: Single condition โ†’ single action block

โœ… if-else: Two-way branching (true path + false path)

โœ… else-if ladder: Multi-way branching for mutually exclusive conditions (evaluated top-to-bottom)

โœ… Nested if-else: Conditions within conditions (hierarchical logic)

โœ… Traditional switch: Exact-value matching with break and default; beware of fall-through!

โœ… Enhanced switch (14+): Arrow syntax (->) eliminates fall-through; supports comma-grouped cases

โœ… Switch expressions (14+): Return values using arrow or yield; must be exhaustive

โœ… Decision guide: if-else for ranges/complex logic; switch for discrete exact values

โœ… Valid switch types: byte, short, int, char, String, enum โ€” NOT long, float, double, boolean

๐Ÿ“ฑ Code Tweet (Summary in 280 Characters)

@JavaStudent

Java conditionals in one tweet:
๐Ÿ”น if โ†’ one path
๐Ÿ”น if-else โ†’ two paths
๐Ÿ”น else-if โ†’ many paths (ranges)
๐Ÿ”น switch โ†’ many paths (exact values)
๐Ÿ”น switch 14+ โ†’ no fall-through ๐ŸŽ‰
๐Ÿ”น switch expression โ†’ returns values
โ˜• Always use break. Or just use arrows! โ†’

Section M

Earning Checkpoint โ€” Self-Assessment

Skill / TopicTool / ConceptPortfolio EvidenceEarn-Ready?
if / if-else / else-ifJava (conditional statements)GradeCalculator.javaโœ… Yes โ€” foundation of all logic
Nested if-elseHierarchical decision-makingArmy Eligibility Checkerโœ… Yes โ€” used in loan/eligibility engines
Traditional switch-caseJava (break, default, fall-through)SimpleATM.java, DayOfWeekPrinter.javaโœ… Yes โ€” menu-driven apps
Enhanced switch (14+)Arrow syntax, switch expressions, yieldSeason finder, HTTP status mapperโœ… Yes โ€” modern Java code
Combined if + switchReal-world logic combining bothIndianRailwayFareCalculator.javaโœ… Yes โ€” portfolio-ready project
Fall-through understandingMCQ mastery, debugging skills30 MCQ practiceโœ… Yes โ€” interview-ready
Rule-based calculator appsJava + conditional logicTax/Fare/Discount calculatorsโœ… Yes โ€” โ‚น2Kโ€“โ‚น5K/project freelance
Minimum Viable Earning Setup after this unit: A GitHub portfolio with 3-5 Java programs (GradeCalculator, SimpleATM, IRCTCFareCalculator, TaxCalculator) + an Internshala profile mentioning "Java programming" = ready to earn โ‚น5Kโ€“โ‚น15K/month from assignments, freelance gigs, and tutoring.

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

[QR: Link to EduArtha video tutorial โ€” Java Conditional Statements]