Branching statements

Intro

Problem

  • Что если нужно досрочно прервать цикл?

  • Что если нужно пропустить какую-то итерацию или ее часть?

Solution

Использовать операторы прерывания

Control Flow Statements

Branching statements

Control Flow Statements

break statement

break statement

Block schema

break in switch

Block schema

break in loop

Block schema

Example

// for loop
for (int i = 1; i <= 10; i++) {
    // if the value of i is 5 the loop terminates
    if (i == 5) {
        break;
    }
    System.out.println(i);
}
1
2
3
4

break in inner loop

Block schema

break with labeled block

Block schema

break with inner labeled block

Block schema

loop as labeled block

Labeled <code>break</code> Statement

Example

// the for loop is labeled as first
first:
for (int i = 1; i < 5; i++) {
    // the for loop is labeled as second
    second:
    for (int j = 1; j < 3; j++) {
        System.out.println("i = " + i + "; j = " + j);
        // the break statement breaks the first for loop
        if (i == 2) {
            break first;
        }
    }
}
i = 1; j = 1
i = 1; j = 2
i = 2; j = 1

continue statement

continue statement

Block schema

continue in loop

Block schema

Example

// for loop
for (int i = 1; i <= 10; i++) {
    // if value of i is between 4 and 9
    // continue is executed
    if (i > 4 && i < 9) {
        continue;
    }
    System.out.println(i);
}
1
2
3
4
9
10

continue in inner loop

Block schema

continue in labeled inner loop

Block schema

Example

outer:
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
    if (j > 1) {
        continue outer;
    }
    System.out.println("[" + i + "; " + j + "]");
}

return statement

return statement

  • The return statement exits from the current method.

  • The return statement control flow returns to where the method was invoked.

return statement forms

  • with returns a value

return count++;
  • without returns a value

return;