Java Control Statements¶
Table of Contents¶
- Introduction
- Selection Statements
- Loop Statements
- Special Keywords
- Practice Questions
- Tips for Success
Introduction¶
Control statements are fundamental building blocks in programming that help us make decisions and repeat actions in our code. Think of them as traffic signals and GPS navigation in real life - they help direct the flow of our program.
Selection Statements (Decision Making)¶
1. if...else Statement¶
This is like making a decision in daily life. For example, "If it's raining, take an umbrella; otherwise, wear sunglasses."
flowchart TD
A[Check Condition] -->|true| B[Execute if block]
A -->|false| C[Execute else block]
B --> D[Continue Program]
C --> D
Simple if Statement¶
Use when you only need to execute code under a certain condition.
// Simple if - no else needed
if (temperature > 30) {
System.out.println("Turn on the fan");
}
// Program continues here regardless of condition
if-else Statement¶
Use when you have two alternative actions.
// if-else example
if (isRaining) {
System.out.println("Take an umbrella");
} else {
System.out.println("Wear sunglasses");
}
if-else if Statement¶
Use when you have multiple conditions to check.
// if-else if example
int score = 85;
if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
}
// Note: no else clause needed if no default action is required
if-else if-else Statement¶
Use when you have multiple conditions and need a default action.
// Complete if-else if-else example
int time = 14; // 24-hour format
if (time < 12) {
System.out.println("Good morning!");
} else if (time < 18) {
System.out.println("Good afternoon!");
} else {
System.out.println("Good evening!");
}
Nested if Statements¶
You can place if statements inside other if statements.
// Nested if example
boolean isWeekend = true;
boolean isRaining = false;
if (isWeekend) {
if (isRaining) {
System.out.println("Watch a movie at home");
} else {
System.out.println("Go for a picnic");
}
}
Key Points for if Statements:¶
- The
if
condition must evaluate to a boolean (true/false) else if
andelse
blocks are optional- You can have multiple
else if
blocks - Only one
else
block is allowed, and it must be last - Curly braces
{}
are optional for single statements but recommended for clarity - Nested if statements should be used carefully to maintain code readability
2. switch Statement¶
Think of this as a menu selection in a restaurant - based on your choice, different actions are taken. The switch statement can only be used with: - integers (int, byte, short, char) - Strings (since Java 7) - enum types
flowchart TD
A[Check Value] --> B{Match Case?}
B -->|Case 1| C[Execute Case 1]
B -->|Case 2| D[Execute Case 2]
B -->|Case 3| E[Execute Case 3]
B -->|No Match| F[Execute Default]
C --> G[Continue Program]
D --> G
E --> G
F --> G
Basic Structure:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
default: // optional
// code block for none matching cases
}
Example with String:
// Coffee vending machine selection
String coffeeChoice = "latte";
switch (coffeeChoice) {
case "espresso":
System.out.println("Preparing short, strong coffee");
break;
case "latte":
System.out.println("Adding steamed milk to espresso");
break;
default: // optional default case
System.out.println("Selection not available");
}
Example with int:
// Day of week example
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
// Notice: no default case needed if no default action required
}
Comparing if-else vs switch¶
Let's look at the same problem solved with both approaches:
Scenario: Determining grade based on letter grade (A, B, C, D, F)
Using if-else:
char grade = 'B';
if (grade == 'A') {
System.out.println("Excellent!");
} else if (grade == 'B') {
System.out.println("Good job!");
} else if (grade == 'C') {
System.out.println("Satisfactory");
} else if (grade == 'D') {
System.out.println("Needs improvement");
} else if (grade == 'F') {
System.out.println("Failed");
} else {
System.out.println("Invalid grade");
}
Using switch:
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Good job!");
break;
case 'C':
System.out.println("Satisfactory");
break;
case 'D':
System.out.println("Needs improvement");
break;
case 'F':
System.out.println("Failed");
break;
default:
System.out.println("Invalid grade");
}
When to Use Which?¶
Use switch when: - You're comparing a single variable against several exact values - You have multiple exact values to compare against (like menu choices) - The variable is an int, String, or enum - You want cleaner, more readable code for multiple conditions
Use if-else when: - You need to evaluate complex conditions - You're checking ranges of values - You're checking multiple variables - You need to use logical operators (AND, OR) - You're working with boolean conditions
Key Points for switch:¶
- Only works with:
- int
- String
- Default case is optional
- Break statements are important to prevent fall-through
- Case values must be constants or literals
- Multiple cases can share the same code block
Loop Statements (Repetition)¶
1. while Loop¶
A while loop repeats a block of code as long as a specified condition remains true. Think of it like: "While a condition is true, keep doing something."
flowchart TD
A[Start] --> B{Check Condition}
B -->|True| C[Execute Loop Body]
C --> D[Update Condition]
D --> B
B -->|False| E[Continue Program]
Basic Structure:¶
while (condition) {
// code block to be executed
// must include something that will eventually make the condition false
}
Condition Rules:¶
- Must evaluate to a boolean (true/false)
- Can include:
- Comparison operators:
<
,>
,<=
,>=
,==
,!=
- Logical operators:
&&
(AND),||
(OR),!
(NOT) - Boolean variables
- Method calls that return boolean
- Comparison operators:
Common Condition Patterns:¶
- Counter-based:
int count = 1; // Initialize
while (count <= 5) { // Check condition
System.out.println("Count is: " + count);
count++; // Update condition
}
- Boolean flag:
boolean isRunning = true;
while (isRunning) {
// Do something
if (someCondition) {
isRunning = false; // Exit condition
}
}
- Complex condition:
int score = 0;
boolean hasLives = true;
while (score < 100 && hasLives) {
// Game logic
score += 10;
if (hitObstacle) {
hasLives = false;
}
}
Real-world Examples:¶
- ATM Machine:
double balance = 1000;
while (balance > 0) {
// Process withdrawal
double withdrawal = getWithdrawalAmount(); // Some method to get amount
if (withdrawal <= balance) {
balance -= withdrawal;
System.out.println("Remaining balance: " + balance);
} else {
System.out.println("Insufficient funds");
}
}
- Reading User Input:
Scanner scanner = new Scanner(System.in);
String input = "";
while (!input.equals("quit")) {
System.out.println("Enter command (type 'quit' to exit):");
input = scanner.nextLine().toLowerCase();
// Process command
}
- Processing a Queue:
Queue<String> messageQueue = new LinkedList<>();
while (!messageQueue.isEmpty()) {
String message = messageQueue.poll();
// Process message
}
Common Patterns and Their Uses:¶
- Pre-condition Check:
- Sentinel Value:
int value = -1;
while (value != 0) { // 0 is the sentinel value
value = getUserInput();
processValue(value);
}
- Input Validation:
int userAge = -1;
while (userAge < 0 || userAge > 120) {
System.out.println("Enter valid age (0-120):");
userAge = scanner.nextInt();
}
Important Considerations:¶
-
Infinite Loop Prevention:
- Always ensure there's a way to make the condition false
- Common causes of infinite loops:
// WRONG: Condition never changes
while (x == 1) {
System.out.println("Hello");
}
// CORRECT: Condition can change
while (x == 1) {
System.out.println("Hello");
x = getUserInput();
}
- Loop Variable Scope:
// Variable accessible only within loop
while (condition) {
int tempValue = 0; // Only exists inside loop
}
// tempValue not accessible here
// Variable accessible after loop
int counter = 0;
while (condition) {
counter++;
}
// counter still accessible here
-
Loop Control Best Practices:
- Initialize variables before the loop
- Update condition-related variables inside the loop
- Use meaningful variable names
- Consider edge cases
Common Mistakes to Avoid:¶
- Forgetting to update the condition
- Using == for String comparison instead of .equals()
- Infinite loops due to incorrect condition updates
- Not considering edge cases
- Complex conditions that are hard to maintain
2. do-while Loop¶
A do-while loop is similar to a while loop, but it executes the code block at least once before checking the condition. Think of it like "Do this task first, then check if you need to do it again."
flowchart TD
A[Start] --> B[Execute Loop Body]
B --> C[Update Condition]
C --> D{Check Condition}
D -->|True| B
D -->|False| E[Continue Program]
Basic Structure:¶
do {
// code block to be executed
// must include something that will eventually make the condition false
} while (condition); // Note the semicolon!
Key Characteristics:¶
- Always executes at least once
- Condition is checked at the end
- Requires semicolon after while condition
Common Use Cases:¶
- Input Validation:
Scanner scanner = new Scanner(System.in);
int userAge;
do {
System.out.println("Enter your age (1-120):");
userAge = scanner.nextInt();
} while (userAge < 1 || userAge > 120);
- Menu Systems:
int choice;
do {
System.out.println("\n1. Start Game");
System.out.println("2. Load Save");
System.out.println("3. Settings");
System.out.println("0. Exit");
choice = scanner.nextInt();
switch(choice) {
case 1: startGame(); break;
case 2: loadSave(); break;
case 3: showSettings(); break;
case 0: System.out.println("Goodbye!"); break;
default: System.out.println("Invalid choice!");
}
} while (choice != 0);
- Retry Logic:
boolean success;
do {
success = tryToConnectToServer();
if (!success) {
System.out.println("Connection failed, retrying...");
Thread.sleep(1000); // Wait 1 second
}
} while (!success);
Comparing while and do-while Loops¶
Let's compare these loops with examples to understand when to use each:
- Basic Difference:
// While Loop - might never execute
int x = 10;
while (x < 5) {
System.out.println("This will never print");
}
// Do-while Loop - always executes at least once
int y = 10;
do {
System.out.println("This will print once");
} while (y < 5);
- Input Validation Example:
Using while loop:
// While Loop Version
Scanner scanner = new Scanner(System.in);
int score = -1; // Invalid initial value
while (score < 0 || score > 100) {
System.out.println("Enter score (0-100):");
score = scanner.nextInt();
}
Using do-while loop:
// Do-while Loop Version
Scanner scanner = new Scanner(System.in);
int score;
do {
System.out.println("Enter score (0-100):");
score = scanner.nextInt();
} while (score < 0 || score > 100);
- Processing Example:
Using while loop:
// While Loop Version - checks before processing
String command = getInitialCommand();
while (!command.equals("quit")) {
processCommand(command);
command = getNextCommand();
}
Using do-while loop:
// Do-while Loop Version - processes first, then checks
String command;
do {
command = getNextCommand();
processCommand(command);
} while (!command.equals("quit"));
When to Use Which:¶
Use while loop when: - You need to check the condition BEFORE the first execution - The loop might not need to run at all - You're working with pre-initialized variables - You're processing data that might be empty from the start
Example scenario:
// Good while loop use case - checking queue
while (!messageQueue.isEmpty()) {
Message msg = messageQueue.poll();
processMessage(msg);
}
Use do-while loop when: - You need to execute the code AT LEAST once - You're validating user input - You're creating menu-driven programs - You're implementing retry logic
Example scenario:
// Good do-while loop use case - menu system
do {
displayMenu();
choice = getUserChoice();
processChoice(choice);
} while (choice != EXIT_CHOICE);
Common Pitfalls:¶
- Forgetting the Semicolon:
// WRONG
do {
// code
} while (condition) // Missing semicolon
// CORRECT
do {
// code
} while (condition); // Has semicolon
- Infinite Loops:
// WRONG - Condition never changes
do {
System.out.println("Infinite loop!");
} while (true);
// CORRECT - Has exit condition
do {
System.out.println("Enter 'exit' to quit:");
input = scanner.nextLine();
} while (!input.equals("exit"));
- Condition Variable Initialization:
// WRONG - variable might not be initialized
int choice;
do {
processChoice(choice); // choice might be undefined
} while (choice != 0);
// CORRECT - variable is always initialized before use
int choice;
do {
choice = getUserChoice();
processChoice(choice);
} while (choice != 0);
3. for Loop¶
A for loop is used when you know the exact number of iterations needed. Think of it as "Do something a specific number of times."
flowchart TD
A[Start] --> B[Initialize Counter]
B --> C{Check Condition}
C -->|True| D[Execute Loop Body]
D --> E[Update Counter]
E --> C
C -->|False| F[Continue Program]
Basic Structure:¶
Each part has a specific purpose:
- initialization: Executed once at the start
- condition: Checked before each iteration
- update: Executed after each iteration
Common For Loop Patterns:¶
- Basic Counting:
// Count up
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i); // Prints 0,1,2,3,4
}
// Count down
for (int i = 5; i > 0; i--) {
System.out.println("Count: " + i); // Prints 5,4,3,2,1
}
- Step Values:
- Multiple Variables:
// Using multiple counters
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println("i = " + i + ", j = " + j);
}
Real-world Examples:¶
- Processing Array Elements:
String[] fruits = {"Apple", "Banana", "Orange"};
for (int i = 0; i < fruits.length; i++) {
System.out.println("Processing fruit: " + fruits[i]);
}
- Building a Multiplication Table:
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.printf("%4d", i * j);
}
System.out.println();
}
- Processing Fixed-Size Data:
// Processing monthly data
for (int month = 1; month <= 12; month++) {
double sales = getMonthlySales(month);
System.out.println("Month " + month + ": $" + sales);
}
Comparing for vs while Loops¶
Let's compare these loops with examples:
- Simple Counter:
Using for loop:
Using while loop:
- Array Processing:
Using for loop:
Using while loop:
When to Use Which:¶
Use for loop when:
- Number of iterations is known beforehand
- Iterating over arrays or collections with known size
- Counter variable is only needed within the loop
- You have a clear initialization, condition, and update pattern
Example scenarios:
// Good for loop use cases
// 1. Fixed number of iterations
for (int i = 1; i <= 10; i++) {
System.out.println("Step " + i);
}
// 2. Array processing
for (int i = 0; i < array.length; i++) {
process(array[i]);
}
// 3. Multiple counters
for (int i = 0, j = 10; i < j; i++, j--) {
System.out.println(i + " " + j);
}
Use while loop when:
- Number of iterations is unknown
- Loop condition depends on user input
- Loop condition is complex
- Counter variable needs to be used after the loop
Example scenarios:
// Good while loop use cases
// 1. User input
while (!userInput.equals("quit")) {
userInput = scanner.nextLine();
}
// 2. Complex condition
while (isConnected && !errorOccurred && hasData) {
processData();
}
// 3. Counter needed later
int attempts = 0;
while (attempts < maxAttempts && !success) {
success = tryOperation();
attempts++;
}
// attempts variable used here
System.out.println("Took " + attempts + " attempts");
Special Features of for Loops:¶
- Scope of Variables:
// Counter only exists in loop
for (int i = 0; i < 5; i++) {
// i is only accessible here
}
// i is not accessible here
// Vs while loop where counter must be declared outside
int i = 0;
while (i < 5) {
i++;
}
// i is still accessible here
- Optional Components:
// All parts are optional
for (;;) {
// Infinite loop
}
// Initialization outside
int i = 0;
for (; i < 5; i++) {
// Loop body
}
// Update inside
for (int i = 0; i < 5;) {
// Loop body
i++;
}
Common Mistakes and Best Practices:¶
- Off-by-One Errors:
// WRONG - misses last element
for (int i = 0; i < array.length - 1; i++)
// CORRECT
for (int i = 0; i < array.length; i++)
- Modifying Counter in Loop Body:
// WRONG - unpredictable behavior
for (int i = 0; i < 5; i++) {
// ... code ...
i++; // Don't modify counter here
}
// CORRECT - counter modification in update section
for (int i = 0; i < 5; i++) {
// ... code ...
}
- Infinite Loops:
// WRONG - infinite loop
for (int i = 0; i >= 0; i++) {
// Will never end
}
// CORRECT
for (int i = 0; i < specificValue; i++) {
// Will end when i reaches specificValue
}
Special Keywords¶
break¶
- Stops the loop immediately
- Like pressing the emergency stop button on a treadmill
- Used to exit switch statements or loops
Example:
// Stop counting when reaching number 5
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println("Count: " + i);
}
continue¶
- Skips the rest of the current iteration and moves to the next one
- Like skipping a damaged page in a book but continuing to read the rest
Example:
// Skip printing even numbers
for (int i = 1; i <= 5; i++) {
if (i % 2 == 0) {
continue;
}
System.out.println("Odd number: " + i);
}
Practice Questions¶
-
Scenario: You're creating a simple thermostat program. Write an if-else statement that:
- If temperature is above 75°F, turn on AC
- If temperature is below 65°F, turn on heat
- Otherwise, maintain current settings
-
Scenario: Create a coffee shop menu using switch statement with options for:
- "americano"
- "latte"
- "cappuccino"
- Default message for unavailable drinks
-
Scenario: Write a while loop that simulates counting exercises, stopping at 5 repetitions.
-
Scenario: Create a for loop that prints a simple countdown from 10 to 1.
Answer Key¶
-
Temperature Control:
-
Coffee Shop Menu:
-
Exercise Counter:
-
Countdown:
Tips for Success¶
- Start Simple: Begin with basic examples and gradually increase complexity
- Visualize: Draw flow diagrams when stuck to understand the logic better
- Practice Regularly: Try to write at least one small program daily
- Real-world Connection: Relate programming concepts to daily life situations
- Test Different Scenarios: Try your code with various inputs to ensure it works as expected
- Common Mistakes to Avoid:
- Forgetting to increment/decrement in loops (leads to infinite loops)
- Missing break statements in switch cases
- Using = (assignment) instead of == (comparison) in conditions