Practical-9
Write a Java Program that implements the use of break statement.
Introduction
A break statement is a programming construct used in Java to terminate a loop or switch statement. When it is encountered inside a loop or switch, it immediately exits from the loop or switch, respectively. The break statement is typically used in loops, such as while and for loops, when the loop criterion is met or the loop's conditions have been violated. The break statement is also necessary when the loop needs to be terminated early and the break statement can simplify the code in certain cases.
Code
for (int i=0;i<=10;i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
Output
0
1
2
3
4
Explanation
The above code loop through values from 0 to 10 and stops once the value reaches 5 using a break statement, the loop is terminated without printing 5.