Java Control Flow Statements: Conditionals, Loops, and Jumps
Control flow statements are fundamental constructs in Java that dictate the order in which instructions are executed. They enable programs to make decisions, repeat actions, and alter execution paths based on specific conditions. Java primarily offers three categories of control flow statements: selection (conditional), iteration (looping), and jump statements.
Selection Statements
Selection statements allow a program to choose between different execution paths based on whether a condition evaluates to true or false.
The if Statement
The if statement is a basic conditional construct. It can appear in several forms:
-
Simple
if: Executes a block of code only if a specified boolean expression is true. ```javapublic class ConditionalCheck { public static void main(String[] args) { int temperature = 25; if (temperature > 20) { System.out.println("It's a warm day!"); } } }
-
if-else: Provides two execution paths. If the boolean expression is true, theifblock runs; otherwise, theelseblock runs. ```javapublic class ConditionalCheck { public static void main(String[] args) { int score = 85; if (score >= 60) { System.out.println("You passed the exam."); } else { System.out.println("You need to retake the exam."); } } }
-
if-else if-else: Allows for multiple conditional checks, providing more than two execution paths. Execution stops at the first true condition. ```javapublic class ConditionalCheck { public static void main(String[] args) { int grade = 78;
if (grade >= 90) { System.out.println("Excellent (A)"); } else if (grade >= 80) { System.out.println("Very Good (B)"); } else if (grade >= 70) { System.out.println("Good (C)"); } else { System.out.println("Needs Improvement (F)"); } }}
if statements can also be nested, meaning one if statement can be placed inside another. Proper indentation is crucial for readability in nested structures.
The switch Statement
The switch statement provides a more streamlined way to handle multiple selection possibilities, particularly when comparing a single variable against several discrete values. It is often preferred over a long sequence of if-else if statements for clarity.
public class SwitchExample {
public static void main(String[] args) {
int dayOfWeek = 3; // 1 = Monday, 2 = Tuesday, etc.
String dayName;
switch (dayOfWeek) {
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; // Optional for default if it's the last case
}
System.out.println("Today is " + dayName);
String command = "DELETE";
switch (command) {
case "CREATE":
System.out.println("Executing create operation.");
break;
case "READ":
System.out.println("Executing read operation.");
break;
case "UPDATE":
System.out.println("Executing update operation.");
break;
case "DELETE":
System.out.println("Executing delete operation.");
// No break here illustrates fall-through
case "ARCHIVE": // This case would also be executed if command was "DELETE"
System.out.println("Operation logged or archived.");
break;
default:
System.out.println("Unknown command.");
}
}
}
Key points for switch statements:
- The
expressionevaluated in theswitchstatement can be of typebyte,short,char,int, their corresponding wrapper classes (Byte,Short,Character,Integer),String(since Java 7), or anenumtype.long,float,double, andbooleanare not supported. - Each
case valuemust be a constant expression (a literal or afinalvariable). - The
breakstatement is crucial. Without it, execution "falls through" to subsequentcaseblocks until abreakis encountered or theswitchstatement ends. This is known as "fall-through." - The
defaultblock is optional and acts similarly to theelseblock in anif-elsestatement, executing if none of thecasevalues match theexpression. It is typically placed last, but can be anywhere.
Iteration Statements (Loops)
Iteration statements, or loops, allow a block of code to be executed repeatedly as long as a certain condition remains true.
The for Loop
The for loop is used when the number of iterations is known or can be easily determined. Its syntax includes initialization, a termination condition, and an iteration step.
public class ForLoopExample {
public static void main(String[] args) {
// Traditional for loop to count from 1 to 5
System.out.println("Counting from 1 to 5:");
for (int counter = 1; counter <= 5; counter++) {
System.out.println("Current count: " + counter);
}
System.out.println("\nIterating through an array with enhanced for loop:");
int[] numbers = {10, 20, 30, 40, 50};
// Enhanced for loop (for-each loop) introduced in Java 5
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println(); // Newline for clean output
}
}
Structure of a traditional for loop:
- Initialization: Executed once at the beginning of the loop (e.g.,
int counter = 1). - Boolean Expression (Condition): Evaluated before each iteration. If true, the loop body executes. If false, the loop terminates.
- Update Expression: Executed after each iteration of the loop body (e.g.,
counter++).
The enhanced for loop (also known as the for-each loop) simplifies iteration over arrays and collections, making code more readable. It automatically manages the index or iterator.
The while Loop
The while loop repeatedly executes a block of code as long as a boolean condition remains true. It evaluates the condition before executing the loop body, meaning if the condition is initially false, the loop body will never execute.
public class WhileLoopExample {
public static void main(String[] args) {
int countdown = 5;
System.out.println("Starting countdown:");
while (countdown > 0) {
System.out.println(countdown);
countdown--; // Decrement to eventually make the condition false
}
System.out.println("Lift off!");
// Example where the loop body never executes
int x = 10;
int y = 20;
System.out.println("\nChecking a condition that is initially false:");
while (x > y) { // 10 > 20 is false
System.out.println("This message will not appear.");
x++;
}
System.out.println("While loop finished. (Condition was false from start)");
}
}
A common pitfall with while loops is creating an infinite loop if the condition never becomes false.
The do-while Loop
The do-while loop is similar to the while loop, but with one key difference: it executes the loop body at least once before evaluating the condition. The condition is checked at the end of each iteration.
public class DoWhileLoopExample {
public static void main(String[] args) {
int attempts = 0;
do {
System.out.println("Attempting action... (Attempt #" + (attempts + 1) + ")");
attempts++;
} while (attempts < 3); // Loop will run 3 times
System.out.println("Action completed after " + attempts + " attempts.");
// Demonstrating guaranteed single execution
int value = 100;
System.out.println("\nDemonstrating single execution when condition is initially false:");
do {
System.out.println("This runs once, even though " + value + " is not less than 50.");
value++;
} while (value < 50); // Condition is false after the first run
}
}
Notice the semicolon after the while condition in a do-while loop.
Loop Control Statements
Java provides special statements that allow you to modify the flow of execution within loops.
The break Statement
The break statement is used to terminate the enclosing loop (for, while, do-while) or switch statement immediately. Execution then continues with the statement immediately following the terminated construct.
public class BreakExample {
public static void main(String[] args) {
System.out.println("Using break in a single loop:");
for (int i = 0; i < 10; i++) {
if (i == 4) {
System.out.println("Breaking loop when i is 4.");
break; // Exits the for loop
}
System.out.println("i: " + i);
}
System.out.println("Loop finished.");
System.out.println("\nUsing labeled break for nested loops:");
outerLoop: // Label for the outer loop
for (int row = 0; row < 3; row++) {
for (int col = 0; col < 3; col++) {
if (row == 1 && col == 1) {
System.out.println("Breaking from outer loop at (1,1).");
break outerLoop; // Exits the 'outerLoop'
}
System.out.println("Processing (Row: " + row + ", Col: " + col + ")");
}
}
System.out.println("Program continues after labeled break.");
}
}
A labeled break allows you to exit a specific outer loop from within nested loops.
The continue Statement
The continue statement skips the remainder of the current iteration of the innermost loop and proceeds to the next iteration. In a for loop, it jumps to the update expression. In while and do-while loops, it jumps to the boolean expression check.
public class ContinueExample {
public static void main(String[] args) {
System.out.println("Using continue to skip even numbers:");
for (int k = 0; k < 5; k++) {
if (k % 2 == 0) { // If k is even
System.out.println("Skipping even number: " + k);
continue; // Skips the rest of the current iteration
}
System.out.println("Processing odd number: " + k);
}
System.out.println("\nUsing labeled continue in nested loops:");
gameLoop:
for (int level = 1; level <= 3; level++) {
for (int player = 1; player <= 2; player++) {
if (player == 2 && level == 2) {
System.out.println("Player 2 encountered issue at Level 2, skipping to next level.");
continue gameLoop; // Skips current inner loop iteration AND remaining outer loop iterations for current level, moving to next level
}
System.out.println("Level " + level + " - Player " + player + " active.");
}
}
System.out.println("Game simulation finished.");
}
}
Similar to break, continue can also be used with a label to skip to the next iteration of a specific outer loop.