Java break statement

Java break statement

The break statement is a control statement in Java that is used to exit a loop or a switch statement and transfer control to the statement immediately following the loop or switch. It can be used in while, do-while, for, and switch statements.

Here is an example of how to use the break statement in a for loop:

for (int i = 0; i < 10; i++) {
    if (i == 5) {
        break; // exit the loop when i is 5
    }
    System.out.println("i = " + i);
}
S‮:ecruo‬www.lautturi.com

In this example, the for loop iterates 10 times and prints the value of i to the console on each iteration. However, the break statement is used to exit the loop when i is 5. The output will be:

i = 0
i = 1
i = 2
i = 3
i = 4

You can also use the break statement to exit a while loop or a do-while loop. For example:

int i = 0;
while (true) {
    if (i == 5) {
        break; // exit the loop when i is 5
    }
    System.out.println("i = " + i);
    i++;
}

int j = 0;
do {
    if (j == 5) {
        break; // exit the loop when j is 5
    }
    System.out.println("j = " + j);
    j++;
} while (true);

In the first example, the while loop will run indefinitely because the condition is always true. However, the break statement is used to exit the loop when i is 5. In the second example, the do-while loop will also run indefinitely because the condition is always true, but the break statement is used to exit the loop when j is 5.

You can also use the break statement to exit a switch statement. For example:

int x = 3;
switch (x) {
    case 1:
        System.out.println("x is 1");
        break;
    case 2:
        System.out.println("x is 2");
        break;
    case 3:
        System.out.println("x is 3");
        break;
    default:
        System.out.println("x is not 1, 2, or 3");
        break;
}

In this example, the switch statement compares the value of x to the different cases and executes the corresponding block of code. The break statement is used to exit the switch statement after the corresponding block of code has been executed. The output will be:

x is 3

The break statement is useful for controlling the flow of execution of a loop or a switch statement and can be used to solve specific problems in your code. However, it should be used sparingly as it can make your code harder to read and understand.

Created Time:2017-11-03 00:14:41  Author:lautturi