Author: SAI K
Core Java | Java Tutorial
The break statement in Java is used to stop a loop or switch case early. It sends control to the statement that follows the loop or switch, ending the current iteration or case.
The break statement is used to leave a loop or switch case early. It’s useful when you want to stop the loop or switch based on a certain condition.
break;
break statement is reached in a loop or switch, the control leaves the loop or switch.
public class SimpleBreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println("i: " + i);
}
}
}
Explanation: This loop prints numbers from 1 to 4. When i is 5, the break statement ends the loop.
public class BreakInForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 7) {
break;
}
System.out.println("i: " + i);
}
}
}
Explanation: This loop prints numbers from 1 to 6. When i is 7, the break statement ends the loop.
public class BreakInWhileLoop {
public static void main(String[] args) {
int i = 1;
while (i <= 10) {
if (i == 7) {
break;
}
System.out.println("i: " + i);
i++;
}
}
}
Explanation: This loop prints numbers from 1 to 6. When i is 7, the break statement ends the loop.
public class BreakInDoWhileLoop {
public static void main(String[] args) {
int i = 1;
do {
if (i == 7) {
break;
}
System.out.println("i: " + i);
i++;
} while (i <= 10);
}
}
Explanation: This loop prints numbers from 1 to 6. When i is 7, the break statement ends the loop.
public class BreakInSwitchCase {
public static void main(String[] args) {
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;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
default:
System.out.println("Weekend");
break;
}
}
}
Explanation: This program prints "Wednesday" because day is 3. It then exits the switch statement using break.
public class BreakWithLabel {
public static void main(String[] args) {
outerLoop: for (int i = 1; i <= 3; i++) {
for (int j = 1; j <= 3; j++) {
if (j == 2) {
break outerLoop;
}
System.out.println("i: " + i + ", j: " + j);
}
}
}
}
Explanation: This loop uses a label outerLoop. It exits the outer loop when j is 2, ending both loops.
The break statement in Java is a strong tool for stopping loops or switch cases early. Knowing when and how to use break, including with nested loops and labels, helps make your code cleaner and easier to follow.