Control flow statements in Java determine the order in which statements are executed, allowing you to create dynamic and responsive programs. Let’s explore the essential control flow structures: if
, switch
, and loops.
1. if
, else if
, and else
:
The if
statement allows you to conditionally execute a block of code.
int num = 10;
if (num > 0) {
System.out.println("Positive");
} else if (num < 0) {
System.out.println("Negative");
} else {
System.out.println("Zero");
}
2. switch
Statement:
The switch
statement performs multi-way branching based on the value of an expression.
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
// Cases for other days...
default:
System.out.println("Invalid day");
}
3. for
Loop:
The for
loop allows you to repeatedly execute a block of code for a specified number of times.
for (int i = 0; i < 5; i++) {
System.out.println("Iteration: " + i);
}
4. while
Loop:
The while
loop continues to execute a block of code as long as a specified condition is true.
int count = 0;
while (count < 3) {
System.out.println("Count: " + count);
count++;
}
5. do-while
Loop:
The do-while
loop is similar to the while
loop, but it guarantees that the block of code is executed at least once.
int x = 5;
do {
System.out.println("Value of x: " + x);
x--;
} while (x > 0);
6. break
and continue
:
The break
statement is used to exit a loop prematurely, while the continue
statement skips the rest of the loop’s code and proceeds to the next iteration.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println("Value: " + i);
}
7. Nested Loops:
Loops can be nested within each other to create complex control flow patterns.
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
System.out.println("i: " + i + ", j: " + j);
}
}
Conclusion:
Understanding control flow is crucial for directing the execution of your Java programs. Whether making decisions with if
statements, handling multiple cases with switch
, or iterating through code with loops, these control flow structures empower you to create dynamic and responsive applications. As you continue your Java journey, leverage these control flow statements to build efficient and flexible software. Happy coding!