Jumps and Labeled Statements - StarShipTutor/StarshipTutorAPCS GitHub Wiki
Jumps and Labeled Statements
The keywords break, continue and return cause the execution to jump to another location in the code.
A line of code can be tagged with a label
codeLabel:
Break
When the break keyword is encountered execution jumps to the end of the innermost containing while, do, for or switch statement. If the break keyword is followed by a label then execution continues at the labeled line in the code.
break codeLabel; // Jump to labeled line in the code
... // Intervening code will not be executed.
codeLabel: // Labeled line in code
Continue
The continue keyword causes execution to jump to the end of the innermost while, for or do loop and continue from there. If the continue is followed by a label for an enclosing loop execution jumps to the end of that loop and continue from that point.
// Loop count number of even integers in the array arrayName[]
numberOfEvens = 0;
for ( i = 0; i < arrayName.length; i++ )
{
if ( arrayName[i] % 2 != 0 ) continue; // Not an even number
numberOfEvens++;
} / End for loop
Return
The return keyword is used to indicate the return point from a method. When the return keyword is encountered execution returns to the point where the method was called. If the return keyword is followed by a return value then that value is inserted in the calling code replacing the method call and the statement is evaluated with the return value replacing the method call.
public static void main(String[] args)
{
pubic class TheClass ()
{
public String aMethod ()
{
// Some code
if ( something == true )
{
// When return is encountered anywhere in the code
// execution jumps to the end of the enclosing method
return ( "the return text" );
}
// Some more code
} // End aMethod
} // End class TheClass ()
// Begin main () code
TheClass anObject = new TheClass();
System.out.println ( anObject.aMethod () );
/*
* When the return statement is encountered inside aMethod ()
* execution jumps back to where the method call was made.
* The return value is inserted and the statement evaluation continues.
*
* i.e
*
* System.out.println ( anObject.aMethod () );
*
* becomes
*
* System.out.println ( "the return text" );
*
* and println is called with the returned string
*/
} // End main ()