Start of Tutorial > Start of Trail > Start of Lesson | Search |
You saw thebreak
statement in action within theswitch
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:To break out of the statement labeledstatementName: someJavaStatementstatementName
use the following form of thebreak
statement.Labeled breaks are an alternative to thebreak statementName;goto
statement, which is not supported by the Java language.Use the
continue
statement within loops to jump to another statement.The
Note: Thecontinue
statement can only be called from within a loop.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 theString
class'sindexOf
method which uses the labeled form ofcontinue
: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 usereturn
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 ofreturn
: 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 thereturn
keyword:The value returned byreturn ++count;return
must match the type of method's declared return value.When a method is declared
void
use the form ofreturn
that doesn't return a value:return;
Start of Tutorial > Start of Trail > Start of Lesson | Search |