The break Statement in Java
The Java break
statement at a defined situation interrupts the program’s current flow. It passes the control to the statement that follows the terminated statement.
In the Java programming language, we can use the break
statement in two ways. When a break
statement is used within a loop, the loop ends right away, and the code proceeds with the following statement, which is after the loop body. It is also used to end the switch-case
condition when a match happens.
We can use the Java break statement in any loop, such as for
loop, do-while
loop, and while
loop.
For example,
public class DemoBreak {
public static void main(String[] args) {
// for loop
for (int i = 0; i <= 10; i++) {
if (i == 7) {
// using Break Statement
break;
}
System.out.println(i);
}
}
}
Output:
0
1
2
3
4
5
6
The break
statement is encountered when the variable i
is equal to 7 in the above example. Similarly, we can use this for other loops also.
We can use the break statement with switch-case
statements, as shown below.
public class DemoSwitchBreak {
public static void main(String[] args) {
int number = 2;
String name;
switch (number) {
case 1:
name = "Pass";
break;
case 2:
name = "Fail";
break;
default:
name = "Invalid";
break;
}
System.out.println(name);
}
}
Output:
Fail
In the switch-case
statement, we use the break
statement to terminate the block and go to the next line of code whenever a match occurs. If we do not use the break
statement, then it will execute all the cases.