Curriculum
Course: Java Basic
Login

Curriculum

Java Basic

Java Home

0/1

Java Introduction

0/1

Java Get Started

0/1

Java Syntax

0/1

Java Comments

0/1

Java Type Casting

0/1

Java Operators

0/1

Java Booleans

0/1

Java Switch

0/1

Java Break / Continue

0/1

Java Errors and Exception

0/1
Text lesson

Java Break And Continue

Java Break

You may recall encountering the break statement in a previous chapter of this tutorial, where it was utilized to exit a switch statement abruptly.

The break statement is also employed to exit a loop prematurely.

In this example, the loop halts when the value of ‘i’ reaches 4:

Example

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  System.out.println(i);
}

Java Continue

The continue statement interrupts the current iteration within the loop if a specific condition arises and proceeds with the next iteration.

This example omits the assess of 4:

Example

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue;
  }
  System.out.println(i);
}

Break and Continue in While Loop

You can employ both break and continue within while loops:

Break Example

int i = 0;
while (i < 10) {
  System.out.println(i);
  i++;
  if (i == 4) {
    break;
  }
}

Continue Example

int i = 0;
while (i < 10) {
  if (i == 4) {
    i++;
    continue;
  }
  System.out.println(i);
  i++;
}