Loops

While loop

while (expr) {
statements;
}

Do ... while

do {
  statements;
} while (expr);

For loop

for (initial-expr; cond-expr; incr-expr) {
  statements;
}

Jump statements

  • break;  - Break from the loop immediately.
  • continue;  - Continue on to the next iteration of the loop.
  • break LABEL;  - Jump to the statement immediately after the labeled statement (terminate the labeled statement).
  • continue LABEL;  - Jump to the labeled statement (restart a labeled statement or continue execution of a labeled loop)

Examples

int sum = 0;
int i = 1;
while (i < 10) {
    if (i == 3) {
        continue;  // Skip the rest of this loop iteration.
    }
    sum += i;

    if (sum > 15) {
        break;  // Exit the loop.
    }
}

Labels

  • Consists of an identifier followed by a colon
  • Used to identify the statement or block of code that the jump statements refer to
  • If the label is omitted, the jump statements refer to the innermost enclosing loop.

Examples

  • LABEL1: statement;
  • LABEL2: { statements; }

Resources URL: 
notes/java/resources
Sources URL: 
notes/java/sources

See Also