Jumps in Loop
In a loop many times it becomes desirable to skip a part of the loop or leave the loop immediately as soon as a certain condition occurs.For Example,you are searching for a name in a String array,as soons as you find the name you should exit the loop immediately as there is no point in continuing the search.
Jumping out of the loop
Exiting from a loop or switch can be achieved by using break statement.Whenever a break statement is encountered inside a loop,the loop is terminated and the execution of the code following the loop body is continued with.
Example:
In a loop many times it becomes desirable to skip a part of the loop or leave the loop immediately as soon as a certain condition occurs.For Example,you are searching for a name in a String array,as soons as you find the name you should exit the loop immediately as there is no point in continuing the search.
Jumping out of the loop
Exiting from a loop or switch can be achieved by using break statement.Whenever a break statement is encountered inside a loop,the loop is terminated and the execution of the code following the loop body is continued with.
Example:
for(int i=0;i<5;i++) { if(i==3) break; else System.out.println(i); } System.out.println("Hello");
1
2
Hello
Explanation:
When the vaue of i is either 1 or 2..the else block is executed and the value of i is printed. As soon as the value of i becomes 3 the if block executes and loop is exited immediately and the code just after the loop body is executed.
Skipping a part of the loop
Sometimes we want to simply skip a part of the loop as soon as a particular condition is fulfilled. To do this we use continue statement.
Example:
public class ContinueExample { public static void main(String[] args) { for(int i=1;i<=10;i++){ if(i==5){ continue; } System.out.println(i); } } }
Output:
1
2
3
4
6
7
8
9
10
No comments:
Post a Comment