Use of Break And Continue keywords in Java, Break and Continue Keywords in Java


Use of Break And Continue keywords in Java, Break and Continue Keywords in Java


Two keywords, break and continue, can be used in loop statements to provide additional controls. Using break and continue can simplify programming in some cases like sometimes if you don't want to execute the statement after a specific statement.

You can use the keyword break in a switch statement. You can also use break in a loop with the help of a conditional (if) statement to immediately terminate the loop.

The following program demonstrate the effect
of using break in a loop.


public class Test {
public static void main(String st[]) {
int sum = 0;
int num = 0;
while (num < 20) {
num++;
sum += num;
if (sum >= 100)
break;
}

System.out.println("The number is " + num);
System.out.println("The sum is " + sum);
}
}

Output:-

The number is 14
The sum is 105


The above program adds integers from 1 to 20 in this order to sum until sum is greater than or equal to 100. Without the if statement, the program calculates the sum of the numbers from 1 to 20. But with the if statement when the sum becomes less then or equal to 100 the loop has terminate and the output is as follows--

The number is 20
The sum is 210


You can also use the continue keyword in a loop. When it is encountered, it ends the current iteration. Program control goes to the end of the loop body. In other words, continue breaks out of an iteration while the break keyword breaks out of a loop.The following program demonstrate the effect of using continue in a loop.


public class Test {
public static void main(String st[]) {
int sum = 0;
int num = 0;
while (num < 20) {
num++;
if (num == 10 || num == 11)
continue;
sum += num;
}
System.out.println("The sum is " + sum);
}
}

Output:-

The sum is 189


The above program adds integers from 1 to 20 except 10 and 11 to sum. With the if statement in the program, the continue statement is executed when number becomes 10 or 11 and the 10 and 11 numbers are not added to the sum and the output is as follows

The sum is 210

In this case, all of the numbers are added to sum, even when number is 10 or 11. Therefore, the result is 210, which is 21 more than it was with the if statement.



{ 0 comments... read them below or add one }

Post a Comment