0
2.7kviews
Explain break and continue statement with example.
1 Answer
0
244views

Explain break and continue statement with example.
i) continue
a) It terminate only the current iteration of the loop.
b) It will bring the next iteration early.
c) It will not stop the execution of the loop.
d) We cannot use it with a switch statement.
For eg:-
Code:-

public class Main { 
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      // If the number is 2
      // skip and continue
      if (i == 2)
        continue;
      System.out.print(i + " ");
    }
  }
}

Output:- 0 1 3 4 5 6 7 8 9
Here as the if condition checks if the value of i==2 then it skips the loop and continues with next iteration.

ii) break
a) It terminates the entire loop immediately.
b) It will terminate the entire loop early.
c) It will stop the execution of the loop.
d) We can use it with a switch statement.
For eg:-
Code:-

public class Main { 
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) {
      // If the number is 2
      // break and exit
      if (i == 2)
        break;
      System.out.print(i + " ");
    }
  }
}

Output:- 0 1
Here as the if condition checks if the value of i==2 then it ends the entire loop immediately.

Please improve formatting


Please log in to add an answer.