Java

Break and Continue

Java / Break and Continue

Break and Continue

Break

The break statement in Java is used to stop (terminate) a loop or switch statement immediately and move the control to the next statement after it.

Use of break:

  • It is used inside loops like for, while, and do-while
  • It is used in switch statements
  • It stops execution when a specific condition is met
  • It can be used to jump out of a loop or switch blockΒ 

The break statement is used to immediately exit from a loop or switch when a condition is satisfied.

Example

public class Main {

Β public static void main(String[] args) {

Β  Β // for loop starts from 0 and runs until i is less than 10
Β  Β for (int i = 0; i < 10; i++) {

Β  Β  Β // check condition: if i becomes 4
Β  Β  Β if (i == 4) {

Β  Β  Β  Β // break statement stops the loop immediately
Β  Β  Β  Β break;
Β  Β  Β }

Β  Β  Β // prints the value of i
Β  Β  Β System.out.println(i);
Β  Β } Β 
Β }
}

Continue

The continue statement in Java is used to skip the current iteration of a loop when a specified condition occurs and continue with the next iteration.

Use of continue:

  • Used inside loops like for, while, and do-while
  • Skips the current loop execution when a condition is met
  • Continues with the next iteration of the loop

Example

public class Main {

Β public static void main(String[] args) {

Β  Β // for loop starts from 0 and runs until i is less than 10
Β  Β for (int i = 0; i < 10; i++) {

Β  Β  Β // check condition: if i becomes 4
Β  Β  Β if (i == 4) {

Β  Β  Β  Β // continue statement skips this iteration
Β  Β  Β  Β // and moves to the next loop cycle
Β  Β  Β  Β continue;
Β  Β  Β }

Β  Β  Β // prints the value of i
Β  Β  Β System.out.println(i);
Β  Β } Β 
Β }
}

Technology
Java
want to connect with us ?
Contact Us