break Statement
The break statement is used to immediately exit from a loop (for, while, do-while, for-each) or a switch block.
When break is executed, the control jumps out of the current block, and the program continues from the next statement after the loop or switch.
Use Cases:
- To stop a loop when a specific condition is met.
- To exit from a particular case in a switch block.
- To exit early from any loop: for, while, do-while, or for-each.
Example 1: Using break in a for loop
class ShikshaSanchar {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) break;
System.out.println(i);
}
}
}
Output:
1
2
Explanation:
- The loop runs from 1 to 5.
- When i == 3, the break statement executes.
- Control exits the loop immediately, so only 1 and 2 are printed.
Example 2: Using break in a while loop
class ShikshaSanchar {
public static void main(String[] args) {
int i = 1;
while (i <= 5) {
if (i == 3) break;
System.out.println(i);
i++;
}
}
}
Output:
1
2
Explanation:
- Loop continues while i <= 5.
- When i == 3, the loop exits due to break.
- Hence, 1 and 2 are printed before the loop stops.
Example 3: Using break in a do-while loop
class ShikshaSanchar {
public static void main(String[] args) {
int i = 1;
do {
if (i == 3) break;
System.out.println(i);
i++;
} while (i <= 5);
}
}
Output:
1
2
Explanation:
- do-while loop ensures the block runs at least once.
- When i == 3, break stops the loop.
- So, the output is 1 and 2.
Example 4: Using break in a for-each loop
class ShikshaSanchar {
public static void main(String[] args) {
String[] names = {"Simran", "Devanshi", "Angel", "Pihu"};
for (String name : names) {
if (name.equals("Angel")) {
break;
}
System.out.println(name);
}
}
}
Output:
Simran
Devanshi
Explanation:
- The loop goes through each name.
- When "Angel" is found, break stops the loop.
- So, only "Simran" and "Devanshi" are printed.
Example 5: Using break in a switch block
class ShikshaSanchar {
public static void main(String[] args) {
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
}
}
}
Output:
Tuesday
Explanation:
- Since day == 2, it matches case 2.
- "Tuesday" is printed.
- break prevents checking case 3 or further fall-through.
Important Notes:
- In loops, break is helpful for exiting early based on a condition.
- In switch, break prevents execution from continuing to the next case.
- break works in all types of loops: : for, while, do-while, and for-each.
Summary:
- The break statement is used to exit immediately from a loop or switch block.
- It works with all loop types for, while, do-while, and for-each.
- In loops, it stops execution early when a condition is met.
- In switch, it prevents fall-through by exiting after a matching case.
- After brea, control jumps to the next statement outside the loop or switch.