In Java, the break statement has three uses.
- As you have seen it terminates a statement sequence in a switch statement.
- It can be used to exit a loop.
- It can be used as a “civilized” form of goto.
The last two uses are explained here.
Using break to Exit a Loop By using break you can force immediate termination of a loop by-passing the conditional expression and any remaining code in the body of the loop.
When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
// Using break to exit a loop.
class WLBreak
{
public static void main(String args[])
{
for(int i=0; i<10; i++)
{
if(i == 5)
break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
|
Type following command in command prompt
javac WLBreak.java
java WLBreak
i: 0
i: 1
i: 2
i: 3
i: 4
Loop complete.
Here are two other points to remember about break. First, more than one break statement may appear in a loop. However, be careful. Too many break statements have the tendency to de-structure your code. Second, the break that terminates a switch statement affects only that switch statement and not any enclosing loops.
REMEMBER break was not designed to provide the normal means by which a loop is terminated. The loop’s conditional expression serves this purpose. The break statement should be used to cancel a loop only when some sort of special situation occurs.
No comments:
Post a Comment
If you have any query please comment here, Will get back to you :)