|
|
Start of Tutorial > Start of Trail > Start of Lesson | Search |
You saw thebreakstatement in action within theswitchstatement earlier. As noted there,breakcauses the flow of control to jump to the statement immediately following the current statement.Another form of the
breakstatement 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: someJavaStatementstatementNameuse the following form of thebreakstatement.Labeled breaks are an alternative to thebreak statementName;gotostatement, which is not supported by the Java language.Use the
continuestatement within loops to jump to another statement.The
Note: Thecontinuestatement can only be called from within a loop.continuestatement 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
continuestatement continues at the next iteration of the labeled loop. Consider this implementation of theStringclass'sindexOfmethod 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
returnstatement. You usereturnto 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 thereturnkeyword:The value returned byreturn ++count;returnmust match the type of method's declared return value.When a method is declared
voiduse the form ofreturnthat doesn't return a value:return;
|
|
Start of Tutorial > Start of Trail > Start of Lesson | Search |