Java break Statement

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:


\begin{lstlisting}
class Test {
public static void main(String[] args) {
\par
/...
...es
if (i == 5) {
break;
}
System.out.println(i);
}
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
1
2
3
4
\end{lstlisting}

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,


\begin{lstlisting}
if (i == 5) {
break;
}
\end{lstlisting}

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.


\begin{lstlisting}
import java.util.Scanner;
\par
class UserInputSum {
public s...
...r
sum += number;
}
System.out.println(''Sum = '' + sum);
}
}
\end{lstlisting}

Output:


\begin{lstlisting}
Enter a number: 3.2
Enter a number: 5
Enter a number: 2.3
Enter a number: 0
Enter a number: -4.5
Sum = 10.5
\end{lstlisting}

In the above program, the test expression of the while loop is always true. Here, notice the line,


\begin{lstlisting}
if (number < 0.0) {
break;
}
\end{lstlisting}

This means when the user input negative numbers, the while loop is terminated.



Subsections