Java Decision Making: if, else, switch & Expressions Explained (2026)
⏱️ Reading Time: 22 minutes | 🎯 Difficulty: Beginner | 🔄 Last Updated: August 21, 2026
What is Decision Making in Java?
Decision making is the ability of a program to choose between different paths of execution based on whether a condition is true or false.
Without decision making, every program would run the exact same way every time — like a train on a single track with no switches. Decision making adds intelligence to your code.
1int marks = 75; 2 3if (marks >= 40) { 4 System.out.println("Pass"); // This runs because 75 >= 40 is true 5} else { 6 System.out.println("Fail"); // This is skipped 7}
Every decision-making statement evaluates a boolean expression — an expression that results in either true or false.
Why Do Programs Need to Make Decisions?
"I once built a login page that welcomed every user as 'Admin' because I didn't use an if statement. My mentor called it 'the most honest bug ever.'" — Every developer's early story.
Real-world software is nothing but a series of decisions:
| Scenario | Decision Required |
|---|---|
| Banking App | Is the PIN correct? Is the balance sufficient? |
| E-Commerce | Is the coupon valid? Is the item in stock? |
| Student Portal | Did the student pass? What grade do they get? |
| Healthcare | Is the patient eligible for insurance? |
| Gaming | Did the player collide with an enemy? Is the level complete? |
| Authentication | Is the user logged in? Do they have admin rights? |
Java provides four core decision-making tools:
if— Execute code if a condition is trueif...else— Choose between two pathselse ifladder — Choose among many pathsswitch— Choose based on exact values
The if Statement
The if statement is the simplest form of decision making. It executes a block of code only if the condition evaluates to true.
Syntax
1if (condition) { 2 // Code runs ONLY if condition is true 3}
Flow
[Condition?]
/ \
true false
/ \
[Run Code] [Skip Code]
Example: Student Pass Check
1public class IfExample { 2 public static void main(String[] args) { 3 int marks = 75; 4 5 if (marks >= 40) { 6 System.out.println("🎉 Student Passed!"); 7 } 8 9 System.out.println("Program continues..."); 10 } 11}
Output:
1🎉 Student Passed! 2Program continues...
If marks were 35, only "Program continues..." would print — the if block would be skipped entirely.
⚠️ Common Syntax Trap
1// WRONG — Missing braces for multi-line 2if (marks >= 40) 3 System.out.println("Pass"); 4 System.out.println("Congratulations!"); // This ALWAYS runs! 5 6// CORRECT — Always use braces 7if (marks >= 40) { 8 System.out.println("Pass"); 9 System.out.println("Congratulations!"); 10}
Golden Rule: Even for single-line
ifbodies, use braces. It prevents bugs and makes your code readable.
The if...else Statement
Use if...else when you need to choose between two mutually exclusive paths — one for true, one for false.
Syntax
1if (condition) { 2 // Runs if condition is TRUE 3} else { 4 // Runs if condition is FALSE 5}
Example: Voting Eligibility
1public class VotingEligibility { 2 public static void main(String[] args) { 3 int age = 16; 4 5 if (age >= 18) { 6 System.out.println("✅ Eligible to Vote"); 7 } else { 8 System.out.println("❌ Not Eligible. Wait " + (18 - age) + " more year(s)."); 9 } 10 } 11}
Output:
1❌ Not Eligible. Wait 2 more year(s).
Real-World Analogy
A traffic light:
if (light == GREEN)→ Goelse→ Stop
There is no third option. The else catches everything the if does not.
Nested if Statements
A nested if is an if statement inside another if. Use it when conditions depend on each other — the inner condition only matters if the outer condition is already true.
Syntax
1if (condition1) { 2 if (condition2) { 3 // Runs only if BOTH conditions are true 4 } 5}
Example: Driving License Check
1public class DrivingCheck { 2 public static void main(String[] args) { 3 int age = 25; 4 boolean hasLicense = true; 5 boolean isSober = true; 6 7 if (age >= 18) { 8 if (hasLicense) { 9 if (isSober) { 10 System.out.println("🚗 You can drive."); 11 } else { 12 System.out.println("🍺 You are not sober. Do not drive."); 13 } 14 } else { 15 System.out.println("📄 You need a license to drive."); 16 } 17 } else { 18 System.out.println("👶 You are too young to drive."); 19 } 20 } 21}
Output:
1🚗 You can drive.
When to Use Nested if vs Logical AND
You can often replace nested if with &&:
1// Nested if (3 levels deep — hard to read) 2if (age >= 18) { 3 if (hasLicense) { 4 if (isSober) { ... } 5 } 6} 7 8// Better: Combine with && 9if (age >= 18 && hasLicense && isSober) { 10 System.out.println("You can drive."); 11}
Use nested if when each level needs different error messages. Use && when you only care about the final true result.
The else if Ladder
The else if ladder handles multiple mutually exclusive conditions. It checks conditions top-to-bottom and executes the first matching block.
Syntax
1if (condition1) { 2 // Block 1 3} else if (condition2) { 4 // Block 2 5} else if (condition3) { 6 // Block 3 7} else { 8 // Default block (catches everything else) 9}
Example: Grade Calculator
1public class GradeCalculator { 2 public static void main(String[] args) { 3 int marks = 82; 4 5 if (marks >= 90) { 6 System.out.println("Grade: A+ 🌟"); 7 } else if (marks >= 80) { 8 System.out.println("Grade: A 👍"); 9 } else if (marks >= 70) { 10 System.out.println("Grade: B ✔️"); 11 } else if (marks >= 60) { 12 System.out.println("Grade: C 📋"); 13 } else if (marks >= 40) { 14 System.out.println("Grade: D ⚠️"); 15 } else { 16 System.out.println("Result: Fail ❌"); 17 } 18 } 19}
Output:
1Grade: A 👍
Critical Behavior: Top-to-Bottom Execution
Java evaluates else if from top to bottom and stops at the first true condition. Order matters!
1// WRONG — This will NEVER print "A+" because 95 >= 40 first! 2if (marks >= 40) { 3 System.out.println("D"); 4} else if (marks >= 60) { 5 System.out.println("C"); 6} else if (marks >= 90) { 7 System.out.println("A+"); // Dead code! Never reached. 8} 9 10// CORRECT — Most specific first 11if (marks >= 90) { 12 System.out.println("A+"); 13} else if (marks >= 80) { 14 System.out.println("A"); 15} else if (marks >= 70) { 16 System.out.println("B"); 17} // ... and so on
Golden Rule: In
else ifladders, arrange conditions from most specific to least specific (highest threshold to lowest).
The switch Statement
The switch statement selects one block of code from multiple options based on the exact value of a variable. It is cleaner than a long else if ladder when comparing against fixed values.
Syntax
1switch (expression) { 2 case value1: 3 // code 4 break; 5 6 case value2: 7 // code 8 break; 9 10 case value3: 11 // code 12 break; 13 14 default: 15 // code when no case matches 16}
What Can You Switch On?
| Java Version | Allowed Types |
|---|---|
| Java 5+ | byte, short, int, char, enum |
| Java 7+ | String added |
| Java 17+ | Pattern matching for switch (preview) |
Example: Day of the Week
1public class DayOfWeek { 2 public static void main(String[] args) { 3 int day = 3; 4 5 switch (day) { 6 case 1: 7 System.out.println("Monday"); 8 break; 9 case 2: 10 System.out.println("Tuesday"); 11 break; 12 case 3: 13 System.out.println("Wednesday"); 14 break; 15 case 4: 16 System.out.println("Thursday"); 17 break; 18 case 5: 19 System.out.println("Friday"); 20 break; 21 case 6: 22 System.out.println("Saturday"); 23 break; 24 case 7: 25 System.out.println("Sunday"); 26 break; 27 default: 28 System.out.println("Invalid day number"); 29 } 30 } 31}
Output:
1Wednesday
Switch with Strings
1String command = "SAVE"; 2 3switch (command.toLowerCase()) { 4 case "save": 5 System.out.println("💾 Saving file..."); 6 break; 7 case "open": 8 System.out.println("📂 Opening file..."); 9 break; 10 case "exit": 11 System.out.println("👋 Exiting application..."); 12 break; 13 default: 14 System.out.println("❓ Unknown command"); 15}
Understanding break and Fall-Through
The break statement is essential in traditional switch blocks. Without it, Java executes the next case anyway — a behavior called fall-through.
Fall-Through Example (Intentional)
1int month = 3; 2 3switch (month) { 4 case 12: case 1: case 2: 5 System.out.println("Winter ❄️"); 6 break; 7 case 3: case 4: case 5: 8 System.out.println("Spring 🌸"); 9 break; 10 case 6: case 7: case 8: 11 System.out.println("Summer ☀️"); 12 break; 13 case 9: case 10: case 11: 14 System.out.println("Autumn 🍂"); 15 break; 16 default: 17 System.out.println("Invalid month"); 18}
Output:
1Spring 🌸
Fall-Through Bug (Accidental)
1// BUG: Missing break in case 1 2int number = 1; 3 4switch (number) { 5 case 1: 6 System.out.println("One"); 7 // Oops! Forgot break! 8 case 2: 9 System.out.println("Two"); 10 break; 11}
Output:
1One 2Two
⚠️ Critical: Always include
breakunless you intentionally want fall-through behavior. Modern IDEs warn you about missingbreakstatements.
Switch Expressions (Java 14+)
Java 14 introduced switch expressions — a modern, concise, and safer way to write switch. They return a value directly and eliminate the break boilerplate.
Syntax
1var result = switch (expression) { 2 case value1 -> outcome1; 3 case value2 -> outcome2; 4 default -> defaultOutcome; 5};
Key Differences from Traditional Switch
| Feature | Traditional switch | Switch Expression |
|---|---|---|
break required | ✅ Yes | ❌ No (arrow syntax) |
| Returns a value | ❌ No | ✅ Yes |
| Fall-through possible | ✅ Yes | ❌ No (no fall-through) |
| Multiple cases per line | case 1: case 2: | case 1, 2 -> |
| Yield for code blocks | N/A | yield value; |
Example: Season Finder
1public class SeasonFinder { 2 public static void main(String[] args) { 3 int month = 2; 4 5 String season = switch (month) { 6 case 12, 1, 2 -> "Winter ❄️"; 7 case 3, 4, 5 -> "Spring 🌸"; 8 case 6, 7, 8 -> "Summer ☀️"; 9 case 9, 10, 11 -> "Autumn 🍂"; 10 default -> "Invalid Month"; 11 }; 12 13 System.out.println("Season: " + season); 14 } 15}
Output:
1Season: Winter ❄️
Switch Expression with Code Blocks
When a case needs multiple lines, use yield:
1String description = switch (grade) { 2 case "A+" -> { 3 System.out.println("Outstanding!"); 4 yield "Excellent performance"; 5 } 6 case "A" -> "Very good"; 7 case "B" -> "Good"; 8 case "C" -> "Average"; 9 default -> { 10 System.out.println("Needs improvement"); 11 yield "Below average"; 12 } 13};
Recommendation: If you are on Java 14+, always prefer switch expressions over traditional
switch. They are shorter, safer (no accidental fall-through), and more readable.
if vs switch: When to Use What
| Scenario | Use if | Use switch |
|---|---|---|
Range checking (>, <, >=) | ✅ Perfect | ❌ Cannot do it directly |
Exact value matching (==) | ✅ Works | ✅ Cleaner for many values |
Multiple conditions with && / ` | ` | |
Comparing String, enum, int | ✅ Works | ✅ Works (Java 7+ for String) |
| Complex business logic | ✅ Better | ❌ Becomes messy |
| Menu options, commands, states | ⚠️ Verbose | ✅ Ideal |
Decision Tree
Are you checking a single variable against exact values?
├── YES → How many values?
│ ├── 1-2 values → if-else is fine
│ └── 3+ values → switch (or switch expression in Java 14+)
└── NO → Are you using ranges or multiple variables?
├── YES → Use if-else or else-if ladder
└── NO → Use if with logical operators (&&, ||)
Example: When if Wins
1// Range + multiple variables — switch cannot handle this 2if (salary > 50000 && age > 25 && hasDegree) { 3 System.out.println("Loan Approved"); 4}
Example: When switch Wins
1// Many fixed values — switch is cleaner 2switch (menuChoice) { 3 case 1 -> showBalance(); 4 case 2 -> deposit(); 5 case 3 -> withdraw(); 6 case 4 -> transfer(); 7 case 5 -> exit(); 8 default -> System.out.println("Invalid choice"); 9}
Real-World Use Cases
Use Case 1: Tiered Electricity Billing
1import java.util.Scanner; 2 3public class ElectricityBill { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Enter units consumed: "); 7 int units = Integer.parseInt(input.nextLine()); 8 9 double bill; 10 11 if (units <= 100) { 12 bill = units * 2.5; 13 } else if (units <= 300) { 14 bill = (100 * 2.5) + ((units - 100) * 4.0); 15 } else if (units <= 500) { 16 bill = (100 * 2.5) + (200 * 4.0) + ((units - 300) * 6.0); 17 } else { 18 bill = (100 * 2.5) + (200 * 4.0) + (200 * 6.0) + ((units - 500) * 8.0); 19 } 20 21 System.out.printf("Total Bill: ₹%.2f%n", bill); 22 } 23 } 24}
Sample Output:
1Enter units consumed: 250 2Total Bill: ₹850.00
Use Case 2: HTTP Status Code Handler
1public class StatusHandler { 2 public static void main(String[] args) { 3 int statusCode = 404; 4 5 String message = switch (statusCode) { 6 case 200 -> "✅ OK — Request successful"; 7 case 201 -> "✅ Created — Resource created"; 8 case 400 -> "❌ Bad Request — Check your input"; 9 case 401 -> "🔒 Unauthorized — Please log in"; 10 case 403 -> "🚫 Forbidden — Access denied"; 11 case 404 -> "🔍 Not Found — Resource missing"; 12 case 500 -> "💥 Internal Server Error"; 13 default -> "❓ Unknown status code"; 14 }; 15 16 System.out.println(message); 17 } 18}
Use Case 3: Role-Based Access Control
1public class AccessControl { 2 public static void main(String[] args) { 3 String role = "editor"; 4 String resource = "article"; 5 String action = "delete"; 6 7 boolean allowed = false; 8 9 if (role.equals("admin")) { 10 allowed = true; 11 } else if (role.equals("editor") && resource.equals("article")) { 12 allowed = !action.equals("delete"); // Editors cannot delete 13 } else if (role.equals("viewer")) { 14 allowed = action.equals("read"); 15 } 16 17 System.out.println(allowed ? "✅ Access granted" : "❌ Access denied"); 18 } 19}
Common Mistakes
Mistake 1: Using = Instead of ==
1// WRONG — Assignment, not comparison! 2if (x = 5) { // Compiles! Assigns 5 to x, evaluates to 5 (truthy) 3 System.out.println("This always runs!"); 4} 5 6// CORRECT — Comparison 7if (x == 5) { 8 System.out.println("x is exactly 5"); 9}
Tip: Some developers write if (5 == x) so that a typo (5 = x) causes a compile-time error.
Mistake 2: Wrong Order in else-if Ladder
1// WRONG — 95 will never reach "A+" 2if (marks >= 40) { 3 System.out.println("D"); 4} else if (marks >= 60) { 5 System.out.println("C"); 6} else if (marks >= 90) { 7 System.out.println("A+"); // Dead code 8} 9 10// CORRECT — Most specific first 11if (marks >= 90) { 12 System.out.println("A+"); 13} else if (marks >= 60) { 14 System.out.println("C"); 15} else if (marks >= 40) { 16 System.out.println("D"); 17}
Mistake 3: Missing break in switch
1// WRONG — Accidental fall-through 2switch (choice) { 3 case 1: 4 System.out.println("Option 1"); 5 case 2: 6 System.out.println("Option 2"); // Also runs if choice is 1! 7 break; 8} 9 10// CORRECT — Always use break (or switch expressions) 11switch (choice) { 12 case 1: 13 System.out.println("Option 1"); 14 break; 15 case 2: 16 System.out.println("Option 2"); 17 break; 18}
Mistake 4: Deep Nesting (Arrow Anti-Pattern)
1// WRONG — The "Arrow of Death" — unreadable! 2if (a) { 3 if (b) { 4 if (c) { 5 if (d) { 6 // ... 7 } 8 } 9 } 10} 11 12// CORRECT — Flatten with logical operators 13if (a && b && c && d) { 14 // ... 15}
Mistake 5: String Comparison with ==
1// WRONG — Compares memory addresses, not content 2if (input.next() == "yes") { // Usually false! 3} 4 5// CORRECT — Use .equals() for content comparison 6if (input.next().equals("yes")) { 7} 8 9// EVEN BETTER — Case-insensitive 10if (input.next().equalsIgnoreCase("yes")) { 11}
Best Practices
-
Always use braces — Even for single-line
ifbodies. Future edits won't break your logic.1// Good 2if (condition) { 3 doSomething(); 4} -
Order else-if from most specific to least specific — Prevents unreachable code.
-
Prefer switch expressions in Java 14+ — No
break, no fall-through bugs, cleaner syntax. -
Avoid deep nesting — If you have more than 3 levels of
if, refactor. Use early returns or extract methods.1// Instead of deep nesting 2if (!isActive) return; 3if (!hasPermission) return; 4if (!isValid) return; 5// Now process the request -
Always include a
defaultcase inswitch— Handle unexpected values gracefully. -
Use meaningful variable names in conditions — Conditions should read like English.
1// Good 2if (isEligibleForDiscount && hasValidCoupon) 3 4// Bad 5if (x && y) -
Keep conditions simple — If a condition is complex, extract it into a boolean variable or method.
1boolean isBusinessHours = (hour >= 9 && hour <= 17); 2boolean isWeekday = (day != DayOfWeek.SATURDAY && day != DayOfWeek.SUNDAY); 3 4if (isBusinessHours && isWeekday) { 5 processRequest(); 6}
Architecture & Performance Considerations
How switch Works Under the Hood
The Java compiler optimizes switch statements differently based on the data type:
| Data Type | Compilation Strategy | Time Complexity |
|---|---|---|
int, short, byte, char | Jump table (lookup table) | O(1) — constant time |
String | hashCode() + equals() | O(1) average, O(n) worst case |
Sparse int ranges | Binary search on sorted cases | O(log n) |
This means a switch on int can be faster than a chain of if-else comparisons because the JVM jumps directly to the correct case rather than evaluating each condition sequentially.
When if-else is Actually Faster
For 2-3 conditions with complex boolean logic, if-else is often faster because:
- The JVM can predict branches using CPU branch prediction
- No overhead of hash code calculation (for String switch)
- Short-circuiting (
&&,||) skips unnecessary evaluations
Pattern Matching Switch (Java 17+)
Modern Java is evolving switch to support pattern matching:
1// Java 17+ (preview feature) 2String formatted = switch (obj) { 3 case Integer i -> String.format("int %d", i); 4 case String s -> String.format("String %s", s); 5 default -> "Unknown type"; 6};
This brings switch closer to functional programming patterns and makes type-based dispatching elegant.
Practice Programs
Exercise 1: Largest of Three Numbers
1import java.util.Scanner; 2 3public class LargestOfThree { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Enter first number: "); 7 int a = Integer.parseInt(input.nextLine()); 8 9 System.out.print("Enter second number: "); 10 int b = Integer.parseInt(input.nextLine()); 11 12 System.out.print("Enter third number: "); 13 int c = Integer.parseInt(input.nextLine()); 14 15 int largest; 16 17 if (a >= b && a >= c) { 18 largest = a; 19 } else if (b >= a && b >= c) { 20 largest = b; 21 } else { 22 largest = c; 23 } 24 25 System.out.println("Largest number is: " + largest); 26 } 27 } 28}
Exercise 2: Leap Year Checker
1import java.util.Scanner; 2 3public class LeapYear { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Enter a year: "); 7 int year = Integer.parseInt(input.nextLine()); 8 9 boolean isLeap; 10 11 if (year % 400 == 0) { 12 isLeap = true; 13 } else if (year % 100 == 0) { 14 isLeap = false; 15 } else if (year % 4 == 0) { 16 isLeap = true; 17 } else { 18 isLeap = false; 19 } 20 21 System.out.println(year + (isLeap ? " is a leap year! 🗓️" : " is not a leap year.")); 22 } 23 } 24}
Exercise 3: Month Name with switch
1import java.util.Scanner; 2 3public class MonthName { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Enter month number (1-12): "); 7 int month = Integer.parseInt(input.nextLine()); 8 9 String name = switch (month) { 10 case 1 -> "January"; 11 case 2 -> "February"; 12 case 3 -> "March"; 13 case 4 -> "April"; 14 case 5 -> "May"; 15 case 6 -> "June"; 16 case 7 -> "July"; 17 case 8 -> "August"; 18 case 9 -> "September"; 19 case 10 -> "October"; 20 case 11 -> "November"; 21 case 12 -> "December"; 22 default -> "Invalid month"; 23 }; 24 25 System.out.println("Month: " + name); 26 } 27 } 28}
Exercise 4: Simple Calculator with switch
1import java.util.Scanner; 2 3public class CalculatorSwitch { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Enter first number: "); 7 double a = Double.parseDouble(input.nextLine()); 8 9 System.out.print("Enter operator (+, -, *, /): "); 10 char op = input.nextLine().charAt(0); 11 12 System.out.print("Enter second number: "); 13 double b = Double.parseDouble(input.nextLine()); 14 15 double result = switch (op) { 16 case '+' -> a + b; 17 case '-' -> a - b; 18 case '*' -> a * b; 19 case '/' -> (b != 0) ? (a / b) : 0; 20 default -> { 21 System.out.println("Invalid operator"); 22 yield 0; 23 } 24 }; 25 26 if (op == '/' && b == 0) { 27 System.out.println("❌ Cannot divide by zero!"); 28 } else if ("+-*/".indexOf(op) >= 0) { 29 System.out.printf("Result: %.2f%n", result); 30 } 31 } 32 } 33}
Exercise 5: Employee Bonus Eligibility
1import java.util.Scanner; 2 3public class EmployeeBonus { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 System.out.print("Years of service: "); 7 int years = Integer.parseInt(input.nextLine()); 8 9 System.out.print("Current salary: "); 10 double salary = Double.parseDouble(input.nextLine()); 11 12 System.out.print("Performance rating (1-5): "); 13 int rating = Integer.parseInt(input.nextLine()); 14 15 double bonus = 0; 16 boolean eligible = false; 17 18 if (years >= 5) { 19 if (rating >= 4) { 20 eligible = true; 21 bonus = salary * 0.20; // 20% bonus 22 } else if (rating >= 3) { 23 eligible = true; 24 bonus = salary * 0.10; // 10% bonus 25 } 26 } else if (years >= 2 && rating == 5) { 27 eligible = true; 28 bonus = salary * 0.05; // 5% bonus 29 } 30 31 if (eligible) { 32 System.out.printf("✅ Bonus Eligible! Bonus: ₹%.2f%n", bonus); 33 } else { 34 System.out.println("❌ Not eligible for bonus this year."); 35 } 36 } 37 } 38}
Mini Project: Smart Menu System
Build a console-based restaurant ordering system that demonstrates switch expressions, input validation, and nested decision-making.
1import java.util.Scanner; 2 3public class SmartMenuSystem { 4 public static void main(String[] args) { 5 try (Scanner input = new Scanner(System.in)) { 6 double total = 0; 7 boolean ordering = true; 8 9 System.out.println("🍽️ WELCOME TO TECH3 CAFE"); 10 System.out.println("==========================="); 11 12 while (ordering) { 13 System.out.println("\n--- MENU ---"); 14 System.out.println("1. Burger - ₹149"); 15 System.out.println("2. Pizza - ₹299"); 16 System.out.println("3. Pasta - ₹199"); 17 System.out.println("4. Fries - ₹ 79"); 18 System.out.println("5. Soft Drink - ₹ 49"); 19 System.out.println("6. Checkout"); 20 System.out.print("Select item (1-6): "); 21 22 int choice = Integer.parseInt(input.nextLine()); 23 24 switch (choice) { 25 case 1, 2, 3, 4, 5 -> { 26 System.out.print("Quantity: "); 27 int qty = Integer.parseInt(input.nextLine()); 28 29 if (qty <= 0) { 30 System.out.println("❌ Invalid quantity."); 31 continue; 32 } 33 34 double price = switch (choice) { 35 case 1 -> 149; 36 case 2 -> 299; 37 case 3 -> 199; 38 case 4 -> 79; 39 case 5 -> 49; 40 default -> 0; 41 }; 42 43 double lineTotal = price * qty; 44 total += lineTotal; 45 46 String itemName = switch (choice) { 47 case 1 -> "Burger"; 48 case 2 -> "Pizza"; 49 case 3 -> "Pasta"; 50 case 4 -> "Fries"; 51 case 5 -> "Soft Drink"; 52 default -> "Unknown"; 53 }; 54 55 System.out.printf("✅ Added %d x %s = ₹%.2f%n", qty, itemName, lineTotal); 56 } 57 case 6 -> { 58 ordering = false; 59 60 double discount = 0; 61 if (total >= 1000) { 62 discount = total * 0.15; 63 System.out.println("\n🎉 15% discount applied!"); 64 } else if (total >= 500) { 65 discount = total * 0.10; 66 System.out.println("\n🎉 10% discount applied!"); 67 } 68 69 double tax = (total - discount) * 0.05; 70 double grandTotal = total - discount + tax; 71 72 System.out.println("\n========== BILL =========="); 73 System.out.printf("Subtotal: ₹%8.2f%n", total); 74 System.out.printf("Discount: -₹%8.2f%n", discount); 75 System.out.printf("Tax (5%%): +₹%8.2f%n", tax); 76 System.out.println("--------------------------"); 77 System.out.printf("Grand Total: ₹%8.2f%n", grandTotal); 78 System.out.println("=========================="); 79 System.out.println("Thank you! Visit again! 👋"); 80 } 81 default -> System.out.println("❌ Invalid choice. Please select 1-6."); 82 } 83 } 84 } 85 } 86}
What This Project Covers:
switchexpressions for menu selection and pricing- Nested
iffor discount tiers - Input validation (quantity check)
- Formatted output with
printf() - Looping for continuous ordering
- Real-world business logic (tax, discounts)
Summary & Cheat Sheet
Quick Reference
| Statement | Use When | Syntax |
|---|---|---|
if | Single condition | if (cond) { ... } |
if...else | Two paths | if (cond) { ... } else { ... } |
else if | Multiple ranges | if (c1) ... else if (c2) ... else ... |
switch | Exact value matching | switch (x) { case 1: ... break; } |
| Switch Expression | Java 14+, returns value | var r = switch (x) { case 1 -> "A"; }; |
Key Takeaways
ifis universal — Use it for any boolean condition, especially ranges and complex logic.switchis specialized — Use it for exact value matching (menu options, status codes, enums).- Order matters in
else if— Always go from most specific to least specific. breakis critical in traditionalswitch— Forget it, and you get fall-through bugs.- Switch expressions are the future — If you are on Java 14+, use them. They are safer and cleaner.
- Avoid deep nesting — Flatten with
&&/||or extract methods when you exceed 3 levels. - Always handle the
defaultcase — Whether inswitchor as a finalelse, catch unexpected values.
What's Next?
Now that your programs can make decisions, it's time to make them repeat actions:
- Loops (
for,while,do-while) — Process lists, repeat tasks, iterate data - Arrays — Store multiple values and loop through them
- Methods — Organize decision logic into reusable blocks
- Exception Handling — Handle invalid inputs gracefully
Decision making is the brain of your program. Combine it with loops, and you can build anything from a calculator to a full game engine.