Java Programming
Lecture 05: Control Flow - Selection Statements
Course: 4343203 - Java Programming
GTU Semester 4 | Unit 1
Learning Objectives:
- Master if-else conditional statements
- Understand nested and chained conditions
- Learn switch statement and its applications
- Apply conditional logic in practical programs
- Debug common conditional statement errors
Understanding Control Flow Statements
Control Flow Statements determine the execution path of a program by controlling which statements are executed and in what order.
Selection Statements:
- if statement - Single condition
- if-else statement - Two alternatives
- if-else-if ladder - Multiple conditions
- switch statement - Multiple values
Key Concepts:
- Boolean Expression: Condition evaluation
- Code Block: Statements to execute
- Branch: Different execution paths
- Fall-through: Continued execution
Simple if Statement
Syntax:
if (condition) {
// statements to execute if condition is true
}Basic Examples:
int age = 18;
if (age >= 18) {
System.out.println("You are eligible to vote!");
}
int marks = 85;
if (marks >= 90) {
System.out.println("Grade: A+");
}
boolean isLoggedIn = true;
if (isLoggedIn) {
System.out.println("Welcome to your dashboard!");
}Flowchart Logic:
Important Rules:
- Condition must be boolean expression
- Braces {} are optional for single statement
- Always use braces for readability
- No semicolon after closing brace
if-else Statement
Syntax & Examples:
// Basic if-else syntax
if (condition) {
// execute if condition is true
} else {
// execute if condition is false
}
// Examples
int number = 15;
if (number % 2 == 0) {
System.out.println(number + " is even");
} else {
System.out.println(number + " is odd");
}
// Age category example
int age = 25;
if (age < 18) {
System.out.println("Minor");
} else {
System.out.println("Adult");
}
// Grade classification
double percentage = 75.5;
if (percentage >= 60) {
System.out.println("Pass");
} else {
System.out.println("Fail");
}Real-world Application:
// Login validation
String username = "admin";
String password = "secret123";
if (username.equals("admin") && password.equals("secret123")) {
System.out.println("Login successful!");
System.out.println("Redirecting to dashboard...");
} else {
System.out.println("Invalid credentials!");
System.out.println("Please try again.");
}
// Temperature check
double temperature = 38.5;
if (temperature > 37.0) {
System.out.println("You have a fever");
System.out.println("Please consult a doctor");
} else {
System.out.println("Temperature is normal");
System.out.println("Stay healthy!");
}Best Practices:
- Use meaningful variable names
- Keep conditions simple and readable
- Group related statements in blocks
- Avoid deep nesting when possible
Nested if Statements
Simple Nested Example:
int age = 25;
boolean hasLicense = true;
if (age >= 18) {
System.out.println("Age requirement met");
if (hasLicense) {
System.out.println("You can drive!");
} else {
System.out.println("You need a driving license");
}
} else {
System.out.println("You are too young to drive");
}Grade Calculator:
int marks = 85;
if (marks >= 0 && marks <= 100) {
System.out.println("Valid marks");
if (marks >= 90) {
System.out.println("Grade: A+");
} else if (marks >= 80) {
System.out.println("Grade: A");
} else if (marks >= 70) {
System.out.println("Grade: B");
} else if (marks >= 60) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}
} else {
System.out.println("Invalid marks!");
}Complex Nested Logic:
// Banking system example
double balance = 5000.0;
double withdrawAmount = 2000.0;
boolean accountActive = true;
if (accountActive) {
System.out.println("Account is active");
if (withdrawAmount > 0) {
System.out.println("Valid withdrawal amount");
if (balance >= withdrawAmount) {
balance = balance - withdrawAmount;
System.out.println("Withdrawal successful!");
System.out.println("Remaining balance: " + balance);
} else {
System.out.println("Insufficient funds!");
System.out.println("Available balance: " + balance);
}
} else {
System.out.println("Invalid withdrawal amount!");
}
} else {
System.out.println("Account is inactive");
System.out.println("Please contact customer service");
}Nesting Guidelines:
- Limit nesting depth to 3-4 levels
- Use proper indentation
- Consider early returns to reduce nesting
- Break complex conditions into variables
if-else-if Ladder
Syntax & Structure:
if (condition1) {
// Block 1
} else if (condition2) {
// Block 2
} else if (condition3) {
// Block 3
} else {
// Default block
}Grade System Example:
int percentage = 78;
if (percentage >= 90) {
System.out.println("Grade: A+ (Outstanding)");
} else if (percentage >= 80) {
System.out.println("Grade: A (Excellent)");
} else if (percentage >= 70) {
System.out.println("Grade: B (Good)");
} else if (percentage >= 60) {
System.out.println("Grade: C (Satisfactory)");
} else if (percentage >= 50) {
System.out.println("Grade: D (Pass)");
} else {
System.out.println("Grade: F (Fail)");
}Day of Week Example:
int day = 3;
if (day == 1) {
System.out.println("Monday - Start of work week!");
} else if (day == 2) {
System.out.println("Tuesday - Keep going!");
} else if (day == 3) {
System.out.println("Wednesday - Midweek!");
} else if (day == 4) {
System.out.println("Thursday - Almost there!");
} else if (day == 5) {
System.out.println("Friday - TGIF!");
} else if (day == 6) {
System.out.println("Saturday - Weekend fun!");
} else if (day == 7) {
System.out.println("Sunday - Rest day!");
} else {
System.out.println("Invalid day number!");
}BMI Calculator:
double bmi = 22.5;
if (bmi < 18.5) {
System.out.println("Underweight");
} else if (bmi < 25.0) {
System.out.println("Normal weight");
} else if (bmi < 30.0) {
System.out.println("Overweight");
} else {
System.out.println("Obese");
}switch Statement
Syntax & Basic Example:
switch (expression) {
case value1:
// statements
break;
case value2:
// statements
break;
default:
// default statements
break;
}
// Example: Menu selection
int choice = 2;
switch (choice) {
case 1:
System.out.println("Option 1: Create Account");
break;
case 2:
System.out.println("Option 2: Login");
break;
case 3:
System.out.println("Option 3: Exit");
break;
default:
System.out.println("Invalid choice!");
break;
}Month Name Example:
int month = 7;
String monthName;
switch (month) {
case 1: monthName = "January"; break;
case 2: monthName = "February"; break;
case 3: monthName = "March"; break;
case 4: monthName = "April"; break;
case 5: monthName = "May"; break;
case 6: monthName = "June"; break;
case 7: monthName = "July"; break;
case 8: monthName = "August"; break;
case 9: monthName = "September"; break;
case 10: monthName = "October"; break;
case 11: monthName = "November"; break;
case 12: monthName = "December"; break;
default: monthName = "Invalid month"; break;
}
System.out.println("Month: " + monthName);switch Statement Rules:
- Expression must be int, char, String, or enum
- Case values must be compile-time constants
- Each case should end with break (usually)
- default case is optional but recommended
- No duplicate case values allowed
switch Fall-through & Advanced Usage
Fall-through Behavior:
// Without break statements
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
// No break - falls through!
case 2:
System.out.println("Tuesday");
// No break - falls through!
case 3:
System.out.println("Wednesday");
break; // Stops here
default:
System.out.println("Other day");
}
// Output for day = 3:
// WednesdayIntentional Fall-through:
char grade = 'B';
switch (grade) {
case 'A':
case 'B':
case 'C':
System.out.println("Pass");
break;
case 'D':
case 'F':
System.out.println("Fail");
break;
default:
System.out.println("Invalid grade");
}Grouped Cases:
// Days of week grouping
int day = 6;
switch (day) {
case 1:
case 2:
case 3:
case 4:
case 5:
System.out.println("Weekday");
System.out.println("Time to work!");
break;
case 6:
case 7:
System.out.println("Weekend");
System.out.println("Time to relax!");
break;
default:
System.out.println("Invalid day");
}Calculator Example:
double num1 = 10, num2 = 5;
char operator = '+';
double result = 0;
switch (operator) {
case '+':
result = num1 + num2;
System.out.println("Addition: " + result);
break;
case '-':
result = num1 - num2;
System.out.println("Subtraction: " + result);
break;
case '*':
result = num1 * num2;
System.out.println("Multiplication: " + result);
break;
case '/':
if (num2 != 0) {
result = num1 / num2;
System.out.println("Division: " + result);
} else {
System.out.println("Division by zero!");
}
break;
default:
System.out.println("Invalid operator!");
}switch vs if-else-if Comparison
When to Use switch:
- Multiple discrete values to check
- Single variable comparison
- Integer, char, String, or enum types
- Performance matters (compiler optimization)
switch Example:
// Good for switch
int statusCode = 200;
switch (statusCode) {
case 200: System.out.println("OK"); break;
case 404: System.out.println("Not Found"); break;
case 500: System.out.println("Server Error"); break;
default: System.out.println("Unknown"); break;
}When to Use if-else-if:
- Complex boolean expressions
- Range comparisons
- Multiple variables involved
- Different data types
if-else-if Example:
// Better with if-else-if
int age = 25;
double income = 50000;
if (age >= 18 && age <= 25) {
System.out.println("Young adult");
} else if (age >= 26 && income > 30000) {
System.out.println("Working professional");
} else if (age >= 60) {
System.out.println("Senior citizen");
} else {
System.out.println("Other category");
}| Feature | switch Statement | if-else-if Ladder |
|---|---|---|
| Data Types | int, char, String, enum | Any boolean expression |
| Performance | Faster for many cases | Sequential evaluation |
| Flexibility | Limited to equality | Any condition possible |
| Readability | Clean for discrete values | Better for complex logic |
Previous Year Exam Questions
Q1. (GTU Summer 2022) Write a Java program to find the largest of three numbers using nested if statements.
Solution:
public class LargestOfThree {
public static void main(String[] args) {
int num1 = 25, num2 = 35, num3 = 15;
int largest;
// Method 1: Using nested if statements
if (num1 >= num2) {
if (num1 >= num3) {
largest = num1;
} else {
largest = num3;
}
} else {
if (num2 >= num3) {
largest = num2;
} else {
largest = num3;
}
}
System.out.println("Numbers: " + num1 + ", " + num2 + ", " + num3);
System.out.println("Largest number is: " + largest);
// Method 2: Alternative approach with cleaner logic
int max = num1;
if (num2 > max) {
max = num2;
}
if (num3 > max) {
max = num3;
}
System.out.println("Alternative method result: " + max);
}
}Q2. (GTU Winter 2021) Explain the switch statement in Java with an example. What is the purpose of break and default statements?
Solution:
switch Statement Overview:
The switch statement is a multiway branch statement that provides an efficient way to transfer control to different parts of code based on the value of an expression.
Example Program:
public class SwitchExample {
public static void main(String[] args) {
int dayNumber = 3;
String dayName;
switch (dayNumber) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
case 7:
dayName = "Sunday";
break;
default:
dayName = "Invalid day";
break;
}
System.out.println("Day " + dayNumber + " is " + dayName);
}
}Purpose of break Statement:
- Terminates the switch block execution
- Prevents fall-through to subsequent cases
- Transfers control to the statement after the switch block
- Without break, execution continues to next case
Purpose of default Statement:
- Executes when no case matches the switch expression
- Similar to else clause in if-else statements
- Optional but recommended for complete logic
- Can be placed anywhere in switch block
Q3. (GTU Summer 2020) Write a menu-driven Java program using switch statement to perform basic arithmetic operations (addition, subtraction, multiplication, division).
Solution:
import java.util.Scanner;
public class Calculator {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("=== Basic Calculator ===");
System.out.println("1. Addition");
System.out.println("2. Subtraction");
System.out.println("3. Multiplication");
System.out.println("4. Division");
System.out.print("Enter your choice (1-4): ");
int choice = scanner.nextInt();
System.out.print("Enter first number: ");
double num1 = scanner.nextDouble();
System.out.print("Enter second number: ");
double num2 = scanner.nextDouble();
double result = 0;
boolean validOperation = true;
switch (choice) {
case 1:
result = num1 + num2;
System.out.println(num1 + " + " + num2 + " = " + result);
break;
case 2:
result = num1 - num2;
System.out.println(num1 + " - " + num2 + " = " + result);
break;
case 3:
result = num1 * num2;
System.out.println(num1 + " * " + num2 + " = " + result);
break;
case 4:
if (num2 != 0) {
result = num1 / num2;
System.out.println(num1 + " / " + num2 + " = " + result);
} else {
System.out.println("Error: Division by zero is not allowed!");
validOperation = false;
}
break;
default:
System.out.println("Invalid choice! Please select 1-4.");
validOperation = false;
break;
}
if (validOperation && choice >= 1 && choice <= 4) {
System.out.println("Operation completed successfully!");
}
scanner.close();
}
}Practical Programming Examples
Student Grade System:
public class StudentGradeSystem {
public static void main(String[] args) {
String studentName = "John Doe";
int[] marks = {85, 92, 78, 88, 95};
int totalMarks = 0;
// Calculate total marks
for (int mark : marks) {
totalMarks += mark;
}
double average = totalMarks / 5.0;
char grade;
String description;
// Determine grade using if-else-if
if (average >= 90) {
grade = 'A';
description = "Outstanding";
} else if (average >= 80) {
grade = 'B';
description = "Excellent";
} else if (average >= 70) {
grade = 'C';
description = "Good";
} else if (average >= 60) {
grade = 'D';
description = "Satisfactory";
} else {
grade = 'F';
description = "Needs Improvement";
}
// Display results
System.out.println("Student: " + studentName);
System.out.println("Total Marks: " + totalMarks + "/500");
System.out.println("Average: " + average + "%");
System.out.println("Grade: " + grade);
System.out.println("Performance: " + description);
}
}Traffic Light System:
public class TrafficLightSystem {
public static void main(String[] args) {
String lightColor = "yellow";
// Using switch for traffic light logic
switch (lightColor.toLowerCase()) {
case "red":
System.out.println("🔴 RED LIGHT");
System.out.println("STOP! Do not proceed.");
System.out.println("Wait for green light.");
break;
case "yellow":
case "amber":
System.out.println("🟡 YELLOW LIGHT");
System.out.println("CAUTION! Prepare to stop.");
System.out.println("Proceed only if safe.");
break;
case "green":
System.out.println("🟢 GREEN LIGHT");
System.out.println("GO! Proceed safely.");
System.out.println("Watch for pedestrians.");
break;
default:
System.out.println("⚪ UNKNOWN LIGHT");
System.out.println("Traffic light malfunction!");
System.out.println("Proceed with extreme caution.");
break;
}
// Additional safety check
boolean isIntersectionClear = true;
boolean isPedestrianCrossing = false;
if (lightColor.equals("green")) {
if (!isIntersectionClear) {
System.out.println("\n⚠️ WARNING: Intersection not clear!");
}
if (isPedestrianCrossing) {
System.out.println("⚠️ WARNING: Pedestrians crossing!");
}
}
}
}Common Errors & Debugging Tips
Common if-else Errors:
1. Assignment instead of comparison
if (x = 5) { // ❌ Wrong! Assignment
// This causes compilation error
}
if (x == 5) { // ✅ Correct! Comparison
// This works properly
}2. Missing braces
if (condition)
statement1;
statement2; // ❌ Not part of if block!
if (condition) { // ✅ Use braces
statement1;
statement2;
}3. Dangling else
if (x > 0)
if (y > 0)
System.out.println("Both positive");
else // ❌ Belongs to inner if!
System.out.println("x is not positive");Common switch Errors:
1. Missing break statements
switch (day) {
case 1: System.out.println("Monday");
case 2: System.out.println("Tuesday"); // ❌ Falls through!
// Output for day=1: "Monday" and "Tuesday"
}
switch (day) {
case 1: System.out.println("Monday"); break; // ✅
case 2: System.out.println("Tuesday"); break; // ✅
}2. Non-constant case values
int x = 10;
switch (day) {
case x: // ❌ Variable not allowed!
break;
case 1: // ✅ Literal constant OK
break;
}3. Duplicate case values
switch (grade) {
case 'A': System.out.println("Excellent"); break;
case 'A': // ❌ Duplicate case!
System.out.println("Outstanding"); break;
}Debugging Tips:
- Use System.out.println() to trace execution flow
- Check boolean expressions with temporary variables
- Use IDE debugger to step through conditions
- Test with boundary values and edge cases
Hands-on Lab Exercises
Exercise 1: Number Analysis Program
- Create a program that takes an integer input
- Check if the number is positive, negative, or zero
- If positive, check if it's even or odd
- If the number is between 1-100, categorize it as small (1-33), medium (34-66), or large (67-100)
// Template for Exercise 1
public class NumberAnalyzer {
public static void main(String[] args) {
int number = 42; // Test with different values
// TODO: Implement the analysis logic
// Use nested if statements and if-else-if ladder
}
}Exercise 2: Seasonal Activity Recommender
- Create a program using switch statement
- Take a month number (1-12) as input
- Recommend seasonal activities based on the month
- Group months by seasons and suggest appropriate activities
Exercise 3: Simple Banking System
- Create a menu-driven banking program
- Options: Check Balance, Deposit, Withdraw, Exit
- Use switch statement for menu handling
- Use if-else for validation (sufficient funds, positive amounts)
Lecture Summary
Key Concepts Covered:
- if statement for single conditions
- if-else for binary decisions
- Nested if statements for complex logic
- if-else-if ladder for multiple conditions
- switch statement for discrete values
- Fall-through behavior and break statements
- Common errors and debugging techniques
Learning Outcomes Achieved:
- ✅ Master conditional statement syntax
- ✅ Apply appropriate selection structure
- ✅ Handle complex decision logic
- ✅ Debug conditional statement errors
- ✅ Write menu-driven programs
- ✅ Implement real-world decision systems
- ✅ Optimize conditional code structure
Next Lecture: Control Flow - Loop Statements
Topics: for loops, while loops, do-while loops, nested loops, loop control statements
Thank You!
Questions & Discussion
Next: Lecture 06 - Control Flow (Loop Statements)
Course: 4343203 Java Programming
Unit 1: Introduction to Java
GTU Semester 4

