BhauAutomation

Java Control Statements

Control Statements in Java allow you to control the flow of program execution. Using them, you can execute statements conditionally or repeatedly based on certain conditions. They are essential building blocks for any Java program.

📘 Topic: Core Java / Flow Control
Read time: 7 min
📊 Level: Beginner
🎮 Focus: Program Flow Control
📖 Overview

What are Control Statements?

Control statements in Java are statements that determine the flow of execution of a program. They allow you to make decisions, repeat tasks, and control the sequence in which code is executed.

📂 Categories

Types of Control Statements in Java

🧠 Decision-Making 🔄 Looping ⏸️ Branching

Java control statements are broadly classified into three categories:

  • 🧠 Decision-Making Statements: if, if-else, if-else-if ladder, switch
  • 🔄 Looping Statements: for loop, while loop, do-while loop, enhanced for loop (for-each)
  • ⏸️ Branching Statements: break, continue, return
🎮 Control Statements

Decision-Making Statements

📝 If-Else Statement

The if-else statement is used to execute a block of code based on a condition. If the condition is true, the code inside 'if' executes; otherwise, the 'else' block executes. You can also use if-else-if ladder for multiple conditions.

int num = 10; // Simple if if (num > 0) { System.out.println("Positive number"); } // if-else if (num % 2 == 0) { System.out.println("Even number"); } else { System.out.println("Odd number"); } // if-else-if ladder int score = 85; if (score >= 90) { System.out.println("Grade A"); } else if (score >= 75) { System.out.println("Grade B"); } else if (score >= 60) { System.out.println("Grade C"); } else { System.out.println("Grade D"); }

🔀 Switch Statement

The switch statement allows a variable to be tested for equality against a list of values (cases). Each case is followed by the value to be compared to. The break prevents fall-through, and default handles unmatched cases.

int day = 3; String dayName; switch(day) { 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"; } System.out.println("Day: " + dayName); // Java 12+ switch expression (arrow syntax) String month = "MAR"; String season = switch(month) { case "DEC", "JAN", "FEB" -> "Winter"; case "MAR", "APR", "MAY" -> "Summer"; case "JUN", "JUL", "AUG" -> "Monsoon"; case "SEP", "OCT", "NOV" -> "Autumn"; default -> "Unknown"; };

Looping Statements

🔄 For Loop

The for loop executes a block of code for a fixed number of times. It consists of initialization, condition, and increment/decrement parts. It's ideal when you know exactly how many iterations are needed.

// Basic for loop for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); } // Nested for loop (multiplication table) for (int i = 1; i <= 5; i++) { for (int j = 1; j <= 5; j++) { System.out.print(i * j + " "); } System.out.println(); } // Enhanced for loop (for-each) int[] numbers = {10, 20, 30, 40, 50}; for (int num : numbers) { System.out.println("Number: " + num); }

⏩ While Loop

The while loop executes a block of code as long as the condition is true. The condition is checked before each iteration. It's useful when the number of iterations is unknown.

// While loop example int i = 1; while (i <= 5) { System.out.println("Count: " + i); i++; } // Example: Sum of digits int num = 12345; int sum = 0; while (num > 0) { sum += num % 10; num /= 10; } System.out.println("Sum of digits: " + sum);

🔁 Do-While Loop

The do-while loop executes the block of code once before checking the condition, then continues if the condition is true. It guarantees at least one execution of the loop body.

// Do-while loop - executes at least once int i = 1; do { System.out.println("Count: " + i); i++; } while (i <= 5); // Menu-driven program example int choice; Scanner sc = new Scanner(System.in); do { System.out.println("1. Add"); System.out.println("2. Subtract"); System.out.println("3. Exit"); System.out.print("Enter choice: "); choice = sc.nextInt(); switch(choice) { case 1: System.out.println("Add operation"); break; case 2: System.out.println("Subtract operation"); break; } } while (choice != 3);

⏸️ Break and Continue

The break statement exits the loop immediately. The continue statement skips the current iteration and moves to the next. They are used to control loop execution more precisely.

// Break example - exit loop when condition met for (int i = 1; i <= 10; i++) { if (i == 5) { break; // Exit loop when i = 5 } System.out.print(i + " "); } // Output: 1 2 3 4 // Continue example - skip current iteration for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skip printing 3 } System.out.print(i + " "); } // Output: 1 2 4 5 // Labeled break (break outer loop) outer: for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { if (i * j == 4) { break outer; // Breaks both loops } System.out.println(i + "," + j); } }

📤 Return Statement

The return statement is used to exit from a method and optionally return a value to the method caller. It immediately terminates the method execution.

// Return statement example public int add(int a, int b) { return a + b; // Returns sum to caller } public void checkAge(int age) { if (age < 18) { System.out.println("Not eligible"); return; // Exit method early } System.out.println("Eligible"); }
🏆 Best Practices

Best Practices for Control Statements

Use meaningful variable names and proper indentation for readability

Prefer switch statements over multiple if-else chains for multiple equality checks

Avoid infinite loops by ensuring loop conditions eventually become false

Use the enhanced for-loop (for-each) when iterating over arrays/collections

Always include break statements in switch cases to prevent fall-through (unless intentional)

Limit nested loops to 2-3 levels for maintainability