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)
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.
Learning Outcomes โ Bloom's Taxonomy Mapped (12 Outcomes)
| Bloom's Level | Learning Outcome |
|---|---|
| ๐ต Remember | LO-1: List the syntax of if, if-else, switch, and switch expression statements in Java |
| ๐ต Remember | LO-2: Define the purpose of break, default, and yield keywords in switch constructs |
| ๐ต Understand | LO-3: Explain the difference between nested if-else and chained (else-if ladder) conditional structures |
| ๐ต Understand | LO-4: Describe how switch fall-through works and why it causes bugs in traditional switch statements |
| ๐ข Apply | LO-5: Write a GradeCalculator program using nested if-else to assign letter grades from marks |
| ๐ข Apply | LO-6: Implement an IRCTC Fare Calculator using both if-else chains and switch-case statements |
| ๐ข Apply | LO-7: Build a SimpleATM menu-driven program using traditional switch-case with break |
| ๐ Analyze | LO-8: Compare traditional switch (with break) vs enhanced switch (Java 14+ arrow syntax) for readability and safety |
| ๐ Analyze | LO-9: Determine when to use if-else vs switch-case based on the type and number of conditions |
| ๐ Evaluate | LO-10: Evaluate switch fall-through traps in MCQ scenarios and predict output correctly |
| ๐ Evaluate | LO-11: Assess which conditional pattern best solves a given Indian industry problem scenario |
| ๐ด Create | LO-12: Design a complete rule-based fare/discount calculator using multiple conditional constructs for a real-world Indian business scenario |
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
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."); }
= 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."); }
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); } }
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."); }
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.
๐ 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."); } } }
โ ๏ธ 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! }
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 + ")"); } }
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"); }
Key differences from traditional switch:
| Feature | Traditional switch | Enhanced switch (14+) |
|---|---|---|
| Syntax | case X: ... break; | case X -> ... |
| Fall-through | Yes (if break missing) | No (impossible) |
| Multiple values | Stack 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);
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);
๐ 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("โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ"); } }
5. Conditional Logic Design Patterns
Nested if-else vs Chained if-else โ When to Use What?
| Aspect | Nested if-else | Chained if-else (else-if ladder) |
|---|---|---|
| Structure | if inside if โ checks sub-conditions | Sequential top-to-bottom checks |
| Use When | Conditions depend on each other (hierarchical) | Conditions are independent / mutually exclusive |
| Example | Check citizenship โ then age โ then height | Check marks: โฅ90? โฅ80? โฅ70? โฅ60? |
| Readability | Can get messy beyond 3 levels | Cleaner for long condition lists |
| Performance | Skips irrelevant branches early | Checks 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 < 18 | Example: day == 1, month == "JAN" |
Learn by Doing โ 3-Tier Lab: IRCTC Fare Calculator
๐ข Tier 1 โ GUIDED: Basic Fare Calculator (if-else)
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
| Distance | Class | Expected Fare |
|---|---|---|
| 1400 km | 1A | โน5950.00 |
| 1400 km | SL | โน1120.00 |
| 500 km | GEN | โน175.00 |
๐ก Tier 2 โ SEMI-GUIDED: Fare Calculator with switch + Tatkal
Your Mission:
Convert the Tier 1 if-else calculator to use switch-case. Add Tatkal surcharge and senior citizen discount logic.
Hints:
- Use
switch (cls)instead of the if-else chain for the rate lookup - Add a boolean
isTatkalโ if true, add 10% surcharge for AC classes, 15% for SL - Add a boolean
isSeniorโ if true, apply 40% discount on final fare - Print a detailed receipt with all line items
- Handle invalid class in the
defaultcase
๐ด Tier 3 โ OPEN CHALLENGE: Complete IRCTC Booking System
The Brief:
Build a complete terminal-based IRCTC booking system that supports:
- Multiple routes: DelhiโMumbai, MumbaiโChennai, KolkataโDelhi (each with different base fares)
- All 5 classes: 1A, 2A, 3A, SL, GEN with different multipliers
- Tatkal surcharge: Different for AC and Non-AC classes
- Senior citizen discount: 40% for male seniors (60+), 50% for female seniors (58+)
- GST: 5% on total fare
- Meal booking: Optional โ โน150 for Veg, โน200 for Non-Veg (use switch)
- 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.
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";
MCQ Assessment Bank โ 30 Questions (Bloom's Mapped)
Remember / Identify (Q1โQ5)
Which keyword is used to exit a switch-case block in traditional Java switch?
- exit
- stop
- break
- continue
break keyword terminates the switch block. Without it, execution falls through to subsequent cases.Which of these data types CANNOT be used in a Java switch expression?
- int
- String
- float
- char
The default case in a switch statement is:
- Mandatory in every switch
- Always placed at the end
- Optional and can be placed anywhere
- Executed before all other cases
In Java 14+, which keyword is used to return a value from a multi-line switch expression block?
- return
- yield
- break
- output
{ }), yield returns the value. return would exit the entire method, not just the switch.What operator does enhanced switch (Java 14+) use instead of case value:?
- case value =>
- case value ->
- case value ::
- case value >>>
case value -> โ The arrow syntax (->) replaces the colon, eliminates fall-through, and removes the need for break statements.Understand / Explain (Q6โQ10)
What is "fall-through" in a switch statement?
- The switch block fails to compile
- Execution continues to subsequent cases after a match when break is missing
- The default case overrides all other cases
- The switch expression returns null
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.Why can't long be used in a switch statement?
- long values are too large for the JVM to index efficiently in a switch lookup table
- long is a floating-point type
- long cannot be compared with ==
- long was deprecated in Java 14
long is 64-bit and would break these optimizations. Use if-else for long comparisons.What is the advantage of using an else-if ladder over nested if-else for grade calculation?
- Else-if ladders run faster
- Else-if ladders are flatter and more readable for mutually exclusive conditions
- Nested if-else cannot handle multiple conditions
- Else-if ladders don't need boolean expressions
In Java, what happens if all conditions in an if-else-if ladder are false and there is no else block?
- Compilation error
- Runtime exception
- Nothing executes โ the program continues past the ladder
- The first if block executes by default
Why does Java 14+ enhanced switch prevent fall-through?
- It uses arrow syntax (->) which executes only the matched arm
- It automatically adds break statements
- It doesn't support multiple cases
- It only works with String types
->) 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)
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");
- A
- B
- C
- Compilation error
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.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"); }
- One
- OneTwo
- OneTwoThreeDefault
- Compilation error
break statements, so after matching case 1, execution falls through ALL remaining cases including default.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"); }
- Vowel
- Consonant
- VowelConsonant
- Compilation error
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");
- A
- B
- C
- CD
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);
- One
- Two or Three
- Other
- Compilation error
Analyze / Compare (Q16โQ20)
Which approach is more appropriate for checking if a number is within a range (e.g., 1โ100)?
- switch-case
- if-else
- Either works equally well
- Neither โ use a loop
<, >=) which switch does not support. Switch requires exact constant values, making it unsuitable for ranges.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"); }
- B
- BC
- BCD
- BCDE
break which stops execution. Case 4 and default are NOT reached.Why is enhanced switch (Java 14+) considered safer than traditional switch?
- It runs faster
- It eliminates fall-through bugs by design
- It supports more data types
- It allows nested switch expressions
->) 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.What is the output?
int a = 10, b = 20; if (a > b) System.out.print("X"); System.out.print("Y");
- XY
- X
- Y
- Nothing
System.out.print("Y") is NOT inside the if โ it always executes regardless of the condition. This is why you should always use braces!In an IRCTC fare system, if you need to handle 5 discrete travel classes (1A, 2A, 3A, SL, GEN), which is the best construct?
- Nested if-else
- switch-case on String
- Ternary operator chain
- while loop
Evaluate / Judge (Q21โQ25)
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"); }
- Missing break statements only
- Duplicate case labels cause compilation error
- String can't be used in switch
- Missing default case
Which code correctly handles the "dangling else" problem?
- Using braces {} to explicitly define scope
- Adding comments to clarify intent
- Using switch instead of if
- Adding blank lines for readability
Evaluate: "switch is always faster than if-else." Is this true?
- True โ switch uses jump tables internally
- False โ for 2-3 conditions, if-else can be equally fast or faster
- True โ switch skips all non-matching cases
- False โ switch is always slower
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"); }
- D
- DA
- DAB
- A
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; }
- Option A โ if-else is always better
- Option B โ switch is cleaner, more readable, and optimized for exact-match values
- Both are identical in every way
- Neither โ use arrays instead
Create / Design (Q26โQ30)
You need to build a discount calculator: 0-500 โ 0%, 501-2000 โ 5%, 2001-5000 โ 10%, 5001+ โ 15%. Which construct should you use?
- switch-case
- if-else ladder with range comparisons
- Nested switch
- Single if statement
<=, >) which switch cannot handle. An if-else ladder with range checks is the correct and only approach.To create a Java 14+ switch expression that maps HTTP status codes to messages and returns a String, which syntax is correct?
String msg = switch(code) { case 200 -> "OK"; default -> "Unknown"; };switch(code) { case 200: return "OK"; }String msg = switch(code) { case 200: "OK"; default: "Unknown"; };switch(code) -> { case 200 => "OK"; }
Type var = switch(expr) { case val -> result; default -> fallback; }; Note the semicolon at the end โ it's an expression/statement.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"); }
- Zero
- ZeroDef
- ZeroDefOne
- ZeroOne
break exits. Case 1 is NOT reached because of the break in default.You're designing a Zomato-like app. For restaurant filtering, users select: "Veg", "Non-Veg", "Jain", "Vegan", or "Eggetarian". Which construct is most appropriate?
- Nested if-else
- switch on String
- Ternary operator
- for loop with conditions
Which of the following will NOT compile?
switch("hello") { case "hello" -> System.out.println("Hi"); }switch(10L) { case 10L -> System.out.println("Ten"); }switch('A') { case 'A' -> System.out.println("Alpha"); }switch(1) { case 1 -> System.out.println("One"); }
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.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.
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):
- Simple if: Single-condition check. Example: checking if marks โฅ 40 to print "Pass".
- if-else: Two-way branching. Example: eligible/not eligible to vote based on age โฅ 18.
- else-if ladder: Multi-way sequential checking. Example: grade assignment (O, A, B, C, D, F) based on marks ranges.
- Nested if-else: Hierarchical conditions where sub-conditions depend on outer conditions. Example: Army eligibility checking citizenship โ age โ height.
- Traditional switch-case: Multi-way exact-value matching with break/default. Example: ATM menu (1=Balance, 2=Withdraw, etc.).
- 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):
- Complete working Java program with Scanner input
- switch-case for travel class (1A/2A/3A/SL/GEN) โ rate multiplier
- if-else for Tatkal surcharge (different for AC vs non-AC classes)
- if-else for senior citizen discount (40% off)
- Formatted receipt output with all line items
- 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):
- Traditional switch (Java 1.0): Colon syntax, break required, fall-through by default, limited to int/char.
- Switch on String (Java 7): Added String support. Internally converts to hashCode() comparisons.
- Enhanced switch with arrows (Java 14): Arrow syntax (
->), no fall-through, comma-separated case labels. - Switch expressions (Java 14): Switch can now return a value. Use
yieldfor multi-line blocks. Must be exhaustive (cover all possible values). - 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.
- Code examples comparing old vs new syntax for the same problem.
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).
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."
| Detail | Info |
|---|---|
| Tools Used Daily | Java 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 Java | TCS, Infosys, Wipro, HCL, Cognizant, Capgemini, JP Morgan, Goldman Sachs, Amazon, Flipkart |
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
| Platform | Best For | Typical Rate |
|---|---|---|
| Internshala | Java internships & freelance | โน2,000โโน8,000/project |
| Fiverr | Java programming tasks | $10โ$50/gig |
| Chegg / Course Hero | Answering Java questions | โน100โโน300/answer |
| GitHub Portfolio | Showcasing projects for job applications | Indirect โ leads to โน4โ8 LPA job |
| WhatsApp/College | Helping batchmates with assignments | โน200โโน1,000/assignment |
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! โ
Earning Checkpoint โ Self-Assessment
| Skill / Topic | Tool / Concept | Portfolio Evidence | Earn-Ready? |
|---|---|---|---|
| if / if-else / else-if | Java (conditional statements) | GradeCalculator.java | โ Yes โ foundation of all logic |
| Nested if-else | Hierarchical decision-making | Army Eligibility Checker | โ Yes โ used in loan/eligibility engines |
| Traditional switch-case | Java (break, default, fall-through) | SimpleATM.java, DayOfWeekPrinter.java | โ Yes โ menu-driven apps |
| Enhanced switch (14+) | Arrow syntax, switch expressions, yield | Season finder, HTTP status mapper | โ Yes โ modern Java code |
| Combined if + switch | Real-world logic combining both | IndianRailwayFareCalculator.java | โ Yes โ portfolio-ready project |
| Fall-through understanding | MCQ mastery, debugging skills | 30 MCQ practice | โ Yes โ interview-ready |
| Rule-based calculator apps | Java + conditional logic | Tax/Fare/Discount calculators | โ Yes โ โน2Kโโน5K/project freelance |
โ Unit 4 complete. MCQs: 30. Ready for Unit 5!
[QR: Link to EduArtha video tutorial โ Java Conditional Statements]