The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search

Trail: Learning the Java Language
Lesson: The Nuts and Bolts of the Java Language

Branching Statements

You saw the break statement in action within the switch statement earlier. As noted there, break causes the flow of control to jump to the statement immediately following the current statement.

Another form of the break statement causes flow of control to break out of a labeled statement. You label a statement by placing a legal Java identifier (the label) followed by a colon (:) before the statement:

statementName: someJavaStatement
To break out of the statement labeled statementName use the following form of the break statement.
break statementName;
Labeled breaks are an alternative to the goto statement, which is not supported by the Java language.

Use the continue statement within loops to jump to another statement.


Note: The continue statement can only be called from within a loop.
The continue statement has two forms: unlabeled and labeled. If you use the unlabelled form, the loop skips to the end of the loop's body and evaluates the loop's test.

The labeled form of the continue statement continues at the next iteration of the labeled loop. Consider this implementation of the String class's indexOf method which uses the labeled form of continue:

public int indexOf(String str, int fromIndex) {
    char[] v1 = value;
    char[] v2 = str.value;
    int max = offset + (count - str.count);
  test:
    for (int i = offset + ((fromIndex < 0) ? 0 : fromIndex);
         i <= max ; i++)
    {
        int n = str.count;
        int j = i;
        int k = str.offset;
        while (n-- != 0) {
            if (v1[j++] != v2[k++]) {
                continue test;
            }
        }    
        return i - offset;
    }
    return -1;
}

The last of Java's branching statements the return statement. You use return to exit from the current method and jump back to the statement within the calling method that follows the original method call. There are two forms of return: one that returns a value and one that doesn't. To return a value, simply put the value (or an expression that calculates the value after the return keyword:

return ++count;
The value returned by return must match the type of method's declared return value.

When a method is declared void use the form of return that doesn't return a value:

return;

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search