Java Break Statement

🔷 What is the break statement?

The break statement in Java is used to exit a loop or switch statement immediately. When the program encounters a break, it stops the current loop or switch block and jumps to the code that follows it.


🔷 Syntax:

break;

🔷 Where can break be used?

  • Inside for, while, or do-while loops

  • Inside a switch statement


📘 Example 1: Using break in a loop

public class BreakExample {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // Exit the loop when i is 5
}
System.out.println("i = " + i);
}
System.out.println("Loop stopped.");
}
}

Output:

i = 1
i = 2
i = 3
i = 4
Loop stopped.

🔎 Explanation:
As soon as i == 5, the break statement stops the loop execution.


📘 Example 2: Using break in a switch

public class BreakInSwitch {
public static void main(String[] args) {
int num = 2;

switch (num) {
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
default:
System.out.println("Other");
}
}
}

Output:

Two

✅ Note: Without break, the code would continue executing all remaining cases (“fall-through”).

Related Posts