Java break Statement

The break statement is used within loops. When the break statement is encountered, control immediately comes out of the loop. The break statement is used to force early termination of a loop.

We will illustrate the use of break statement through the following code snippet which prints numbers from 1 to 10.

int i = 1;
while (i <= 10) {
    System.out.println(i);
    i++;
}
int i = 1;
do {
    System.out.println(i);
    i++;
} while (i <= 10);
for (int i = 1; i <= 10; i++) {
    System.out.println(i);
}

Here are the modified versions of the above codes which print numbers till 5 only because of the break statement.

int i = 1;
while (i <= 10) {
    System.out.println(i);
    if (i == 5) {
        break;
    }
    i++;
}
int i = 1;
do {
    System.out.println(i);
    if (i == 5) {
        break;
    }
    i++;
} while (i <= 10);
for (int i = 1; i <= 10; i++) {
    System.out.println(i);
    if (i == 5) {
        break;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>