06.Java Break Statement
06.Java Break Statement
In this tutorial, you will learn about the break statement, labeled break
statement in Java with the help of examples.
In such cases, break and continue statements are used. You will learn about
the Java continue statement in the next tutorial.
The break statement in Java terminates the loop immediately, and the control
of the program moves to the next statement following the loop.
It is almost always used with decision-making statements (Java if...else
Statement).
Here is the syntax of the break statement in Java:
break;
// for loop
for (int i = 1; i <= 10; ++i) {
Output:
1
2
3
4
In the above program, we are using the for loop to print the value of i in each
iteration. To know how for loop works, visit the Java for loop. Here, notice the
statement,
if (i == 5) {
break;
}
This means when the value of i is equal to 5, the loop terminates. Hence we
get the output with values less than 5 only.
The program below calculates the sum of numbers entered by the user until
user enters a negative number.
To take input from the user, we have used the Scanner object. To learn more
about Scanner , visit Java Scanner.
import java.util.Scanner;
class UserInputSum {
public static void main(String[] args) {
while (true) {
System.out.print("Enter a number: ");
sum += number;
}
System.out.println("Sum = " + sum);
}
}
Run Code
Output:
In the above program, the test expression of the while loop is always true .
Here, notice the line,
This means when the user input negative numbers, the while loop is
terminated.
We can use the labeled break statement to terminate the outermost loop as
well.
Working of the labeled break
statement in Java
As you can see in the above image, we have used the label identifier to specify
the outer loop. Now, notice how the break statement is used ( break label; ).
Here, the break statement is terminating the labeled statement (i.e. outer
loop). Then, the control of the program jumps to the statement after the
labeled statement.
Here's another example:
while (testExpression) {
// codes
second:
while (testExpression) {
// codes
while(testExpression) {
// codes
break second;
}
}
// control jumps here
}
Output:
i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
In the above example, the labeled break statement is used to terminate the
loop labeled as first. That is,
first:
for(int i = 1; i < 5; i++) {...}
Here, if we change the statement break first; to break second; the program
will behave differently. In this case, for loop labeled as second will be
terminated. For example,
class LabeledBreak {
public static void main(String[] args) {
Output:
i = 1; j = 1
i = 1; j = 2
i = 2; j = 1
i = 3; j = 1
i = 3; j = 2
i = 4; j = 1
i = 4; j = 2