Control Flow
Control flow statements are the building blocks that allow your program to make decisions, repeat actions, and execute code conditionally. In Java, these statements help control which parts of the code run and under what conditions. Here's a breakdown of the main control flow statements.
If-Else Statement
The if-else statement lets you execute code based on a condition. If the condition is true, the code inside the if block runs; if it's false, the code inside the else block runs.
int age = 20; if (age >= 18) { System.out.println("You are an adult."); } else { System.out.println("You are a minor."); }
If-Else-If Ladder: You can use multiple conditions with else if for more complex decision-making.
int score = 85; if (score >= 90) { System.out.println("Excellent!"); } else if (score >= 75) { System.out.println("Good job!"); } else { System.out.println("Keep trying!"); }
Switch Statement
The switch statement is useful when you have multiple possible values for a variable and want different actions for each value. Each case represents a different value, and default runs if none of the cases match.
int day = 3; String dayName; switch (day) { case 1: dayName = "Monday"; break; case 2: dayName = "Tuesday"; break; case 3: dayName = "Wednesday"; break; default: dayName = "Unknown"; } System.out.println(dayName); // Output: Wednesday
For Loop
A for loop is used when you know the exact number of times you want to repeat a block of code. It consists of three parts: initialization, condition, and increment/decrement.
for (int i = 1; i <= 5; i++) { System.out.println("Count: " + i); }
Enhanced For Loop: This is a simplified version of the for loop, often used with arrays and collections.
int[] numbers = {1, 2, 3, 4, 5}; for (int num : numbers) { System.out.println(num); }
While Loop
A while loop keeps repeating as long as a specified condition is true. It’s useful when you don’t know the number of iterations in advance.
int i = 1; while (i <= 5) { System.out.println("Count: " + i); i++; }
Do-While Loop
The do-while loop is similar to the while loop, but it ensures that the code inside runs at least once, even if the condition is false.
int i = 1; do { System.out.println("Count: " + i); i++; } while (i <= 5);
Break and Continue
Break: Exits the loop immediately when encountered
for (int i = 1; i <= 5; i++) { if (i == 3) { break; // Loop stops when i is 3 } System.out.println(i); }
Continue: Skips the current iteration and moves to the next one.
for (int i = 1; i <= 5; i++) { if (i == 3) { continue; // Skips printing 3 } System.out.println(i); }