Break Statement in Java
The break statement in Java is used to exit a loop or a switch statement prematurely. It allows you to control the flow of your program by breaking out of loops or switch cases when certain conditions are met.
Key Points on Break Statement:
- Can be used in for, while, and do-while loops.
- Exits the innermost loop or switch statement that contains it.
- Can be useful for stopping an iteration based on a specific condition.
- When used in a nested loop, it only breaks out of the inner loop.
Syntax of Break Statement:
Syntax Example
break; // Exits the loop or switch statement
Example of Break Statement in a Loop:
This example demonstrates a basic usage of the break statement within a loop.
Code Example 1
public class BreakInLoop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i equals 5
}
System.out.println(i);
}
}
}
Output for Code Example 1:
1
2
3
4
2
3
4
Example of Break Statement in a Switch:
This example shows how to use the break statement within a switch case.
Code Example 2
public class BreakInSwitch {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1:
System.out.println("Monday");
break; // Exit the switch
case 2:
System.out.println("Tuesday");
break; // Exit the switch
case 3:
System.out.println("Wednesday");
break; // Exit the switch
default:
System.out.println("Invalid day");
}
}
}
Output for Code Example 2:
Wednesday
Using Break in Nested Loops:
This example illustrates how the break statement affects nested loops.
Code Example 3
public class NestedLoopBreak {
public static void main(String[] args) {
for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break; // Exits the inner loop when j equals 2
}
System.out.print("i: " + i + ", j: " + j + " | ");
}
System.out.println(); // New line after inner loop
}
}
}
Output for Code Example 3:
i: 1, j: 1 |
i: 2, j: 1 |
i: 3, j: 1 |
i: 2, j: 1 |
i: 3, j: 1 |
Detailed Explanation:
- Usage in Loops: When the break statement is encountered, control is immediately transferred out of the loop.
- Usage in Switch: It prevents fall-through behavior, which would execute all subsequent cases unless a break is encountered.
- Nested Loops: The break statement only exits the innermost loop in which it appears.
The break statement is an essential tool for managing flow control in Java, allowing developers to write more efficient and cleaner code by breaking out of loops or switch cases when needed.