Java Flow Control Statements
Flow control statements in Java are essential for managing the execution flow of a program. They allow developers to make decisions, repeat actions, and control the sequence in which code is executed. By using flow control statements, you can create dynamic and flexible programs that respond to different conditions and inputs.
Types of Flow Control Statements in Java
Java flow control statements can be broadly categorized into three types:
- Decision-Making Statements
- Looping Statements
- Branching Statements
1. Decision-Making Statements
Decision-making statements allow the program to execute specific blocks of code based on certain conditions. These include:
if Statement
The if statement executes a block of code if a specified condition evaluates to true.
Syntax
if (condition) {
// Code to execute if condition is true
}
Example:
int number = 10;
if (number > 0) {
System.out.println("The number is positive.");
}
if-else Statement
The if-else statement provides an alternative block of code to execute if the condition is false.
Syntax:
if (condition) {
// Code to execute if condition is true
}
else {
// Code to execute if condition is false
}
Example:
int number = -5;
if (number > 0) {
System.out.println("The number is positive.");
}
else {
System.out.println("The number is not positive.");
}
if-else-if Ladder
The if-else-if ladder is used to test multiple conditions sequentially.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
}
else {
// Code to execute if none of the conditions are true
}
Example:
int number = 0;
if (number > 0) {
System.out.println("The number is positive.");
}
else if (number < 0) {
System.out.println("The number is negative.");
}
else {
System.out.println("The number is zero.");
}
switch Statement
The switch statement is used to execute one block of code out of many based on the value of an expression.
Syntax:
switch (expression) {
case value1: // Code to execute if expression == value1
break;
case value2: // Code to execute if expression == value2
break; // Additional cases
default: // Code to execute if no case matches
}
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;
default:
System.out.println("Invalid day");
}
Enhanced switch Statement
Java introduced the enhanced switch statement in Java 12 (as a preview feature) and officially finalized it in Java 14. This improvement makes switch statements more concise, readable, and expressive.
Key Enhancements:
Expression-Based Switch:
switchcan now return a value.Multiple Labels (Comma-Separated Cases): One case can handle multiple values.
Arrow (
->) Syntax: Eliminates the need forbreakstatements.Pattern Matching (Preview Feature): Introduced in later versions to allow type-checking.
Example:
public class EnhancedSwitchExample {
public static void main(String[] args) {
String day = "MONDAY";
int numLetters = switch (day) {
case "MONDAY", "FRIDAY", "SUNDAY" -> 6;
case "TUESDAY" -> 7;
default -> 8;
};
System.out.println(numLetters);
}
}
2. Looping Statements
Looping statements allow a block of code to be executed repeatedly based on a condition. Java provides three types of loops:
for Loop
The for loop is used when the number of iterations is known beforehand.
Syntax:
for (initialization; condition; update) {
// Code to execute in each iteration
}
Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
for-each Loop (Enhanced Loop)
The for-each loop (also called the enhanced for loop) in Java is a simpler and more readable way to iterate over collections, arrays, or any Iterable object.
Syntax:
for (Type variable : collection) {
// Code to be executed
}
Example:
public class ForEachArray {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
for (int num : numbers) {
System.out.print(num + " ");
}
}
}
while Loop
The while loop is used when the number of iterations is not known, and the loop continues as long as the condition is true.
Syntax:
while (condition) {
// Code to execute while condition is true
}
Example:
int i = 1;
while (i <= 5) {
System.out.println("Iteration: " + i);
i++;
}
do-while Loop
The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once.
do {
// Code to execute
}
while (condition);
Example:
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 5);
3. Branching Statements
Branching statements are used to alter the normal flow of execution in a program. These include:
break Statement
The break statement is used to exit a loop or a switch statement prematurely.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break; // Exit the loop when i == 3
}
System.out.println("Iteration: " + i);
}
continue Statement
The continue statement skips the current iteration of a loop and proceeds to the next iteration.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) {
continue; // Skip the iteration when i == 3
}
System.out.println("Iteration: " + i);}
return Statement
The return statement is used to exit from a method and optionally return a value.
Example:
public int add(int a, int b) {
return a + b; // Exit the method and return the sum
}
Labelled break and continue
Java allows the use of labels with break and continue to control nested loops.
Example:
outerLoop:
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break outerLoop; // Exit the outer loop
}
System.out.println("i = " + i + ", j = " + j);
}
}
Flow Control Statement Best Practices
- Use meaningful conditions: Ensure that conditions in
if,while, orforstatements are clear and meaningful.- Avoid infinite loops: Always include a termination condition in loops to prevent infinite execution.
- Minimize nested loops: Excessive nesting can make code harder to read and maintain.
- Use
switchfor multiple conditions: When testing a single variable against multiple values, preferswitchoverif-elsefor better readability.
