Java Control Statements

Java Control Statements

Control Statements

 

A programming language uses control statements to cause the flow of execution to advance and branch based on changes to the state of a program. Java’s program control statements can be put into the following categories: selection, iteration, and jump. Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration statements enable program execution to repeat one or more statements that is, iteration statements form loops. Jump statements allow your program to execute in a nonlinear fashion.

 

Java’s Selection Statements

Java supports two selection statements: if and switch. These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

if

The if statement is Java’s conditional branch statement. It can be used to route program execution through two different paths. Here is the general form of the if statement:

 

if (condition)

statement1;

else

statement2;

 

Here, each statement may be a single statement or a compound statement enclosed in curly braces that is, a block. The condition is any expression that returns a boolean value. The else clause is optional.

The if works like this: If the condition is true, then statement1 is executed. Otherwise, statement2  is executed. In no case will both statements be executed. For example, consider the following:

 

int a, b;

// …

if(a < b) a = 0;

else b = 0;

 

Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. In no case are they both set to zero. Most often, the expression used to control the if will involve the relational operators. It is possible to control the if using a single boolean variable, as shown in this code fragment:

 

boolean dataAvailable;

// …

if (dataAvailable)

ProcessData();

else

waitForMoreData();

 

Remember, only one statement can appear directly after the if or the else. If you want to include more statements, you’ll need to create a block, as in this fragment:

 

int bytesAvailable;

// …

if (bytesAvailable > 0) {

ProcessData();

bytesAvailable -= n;

} else

waitForMoreData();

 

Here, both statements within the if block will execute if bytesAvailable is greater than zero. For example, consider the following code fragment:

 

int bytesAvailable;

// …

if (bytesAvailable > 0) {

ProcessData();

bytesAvailable -= n;

} else

waitForMoreData();

bytesAvailable = n;

 

It seems clear that the statement bytesAvailable = n; was intended to be executed inside the else clause, because of the indentation level. The preceding example is fixed in the code that follows:

 

int bytesAvailable;

// …

if (bytesAvailable > 0) {

ProcessData();

bytesAvailable -= n;

} else {

waitForMoreData();

bytesAvailable = n;

}

Nested ifs

A nested if is an if statement that is inside another if or else. Nested ifs are very common in programming. When you nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement. Here is an example:

 

if(i == 10) {

if(j < 20) a = b;

if(k > 100) c = d; // this if is

else a = c; // associated with this else

}

else a = d; // this else refers to if(i == 10)

 

As the comments indicate, the final else is not associated with if(j<20), because it is not in the same block even though it is the nearest if without an else. Rather, the final else is associated with if(i==10). The inner else refers to if(k>100), because it is the closest if within the same block.

The if-else-if Ladder

A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder. It looks like this:

 

if(condition)

statement;

else if(condition)

statement;

else if(condition)

statement;

else

statement;

 

The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is skiped. If none of the conditions is true, then the final else statement will be executed. The final else acts as a default condition; that is, if all other conditional tests fail, then the last else statement is performed. If there is no final else and all other conditions are false, then no action will take place. Here is a program that uses an if-else-if ladder to determine which season a particular month is in.

 

// Demonstrate if-else-if statements.

class IfElse {

public static void main(String args[]) {

int month = 4; // April

String season;

if(month == 12 || month == 1 || month == 2)

season = “Winter”;

else if(month == 3 || month == 4 || month == 5)

season = “Spring”;

else if(month == 6 || month == 7 || month == 8)

season = “Summer”;

else if(month == 9 || month == 10 || month == 11)

season = “Autumn”;

else

season = “Bogus Month”;

System.out.println(“April is in the ” + season + “.”);

}

}

 

Here is the output produced by the program:

April is in the Spring.

switch

The switch statement is Java’s multiway branch statement. It provides an easy way to send execution to different parts of your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if statements. Here is the general form of a switch statement:

 

switch (expression) {

case value1:

// statement sequence

break;

case value2:

// statement sequence

break;

case valueN:

// statement sequence

break;

default:

// default statement sequence

}

 

The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. Each case value must be a unique literal that is, it must be a constant, not a variable. Duplicate case values are not allowed. The switch statement works like this: The value of the expression is compared with each of the literal values in the case statements. If a match is found, the code sequence following that case statement is executed. If none of the constants matches the value of the expression, then the default statement is executed. However, the default statement is optional. If no case matches and no default is present, then no further action is taken. The break statement is used inside the switch to terminate a statement sequence. When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of “jumping out” of the switch. Here is a simple example that uses a switch statement:

 

// A simple example of the switch.

class SampleSwitch {

public static void main(String args[]) {

for(int i=0; i<6; i++)

switch(i) {

case 0:

System.out.println(“i is zero.”);

break;

case 1:

System.out.println(“i is one.”);

break;

case 2:

System.out.println(“i is two.”);

break;

case 3:

System.out.println(“i is three.”);

break;

default:

System.out.println(“i is greater than 3.”);

}

}

}

The output produced by this program is shown here:

i is zero.

i is one.

i is two.

i is three.

i is greater than 3.

i is greater than 3.

 

As you can see, each time through the loop, the statements associated with the case constant that matches i are executed. All others are bypassed. After i is greater than 3, no case statements match, so the default statement is executed. The break statement is optional. If you omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them. For example, consider the following program:

 

// In a switch, break statements are optional.

class MissingBreak {

public static void main(String args[]) {

for(int i=0; i<12; i++)

switch(i) {

case 0:

case 1:

case 2:

case 3:

case 4:

System.out.println(“i is less than 5”);

break;

case 5:

case 6:

case 7:

case 8:

case 9:

System.out.println(“i is less than 10”);

break;

default:

System.out.println(“i is 10 or more”);

}

}

}

This program generates the following output:

i is less than 5

i is less than 5

i is less than 5

i is less than 5

i is less than 5

i is less than 10

i is less than 10

i is less than 10

i is less than 10

i is less than 10

i is 10 or more

i is 10 or more

 

As you can see, execution falls through each case until a break statement or the end of the switch is reached. omitting the break statement has many practical applications in real programs. The example below uses a switch to provide a more efficient implementation.

 

// An improved version of the season program.

class Switch {

public static void main(String args[]) {

int month = 4;

String season;

switch (month) {

case 12:

case 1:

case 2:

season = “Winter”;

break;

case 3:

case 4:

case 5:

season = “Spring”;

break;

case 6:

case 7:

case 8:

season = “Summer”;

break;

case 9:

case 10:

case 11:

season = “Autumn”;

break;

default:

season = “Bogus Month”;

}

System.out.println(“April is in the ” + season + “.”);

}

}

Nested switch Statements

You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer switch. For example, the following fragment is perfectly valid:

 

switch(count) {

case 1:

switch(target) { // nested switch

case 0:

System.out.println(“target is zero”);

break;

case 1: // no conflicts with outer switch

System.out.println(“target is one”);

break;

}

break;

case 2: // …

 

Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch. The count variable is only compared with the list of cases at the outer level. If count is 1, then target is compared with the inner list cases. In summary, there are three important features of the switch statement to note:

  • The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type of Boolean expression. That is, the switch looks only for a match between the value of the expression and one of its case constants.
  • No two case constants in the same switch can have identical values. Of course, a switch statement enclosed by an outer switch can have case constants in common.
  • A switch statement is usually more efficient than a set of nested ifs. When it compiles a switch statement, the Java compiler will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression. Therefore, if you need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-elses.

 

Iteration Statements

Java’s iteration statements are for, while, and do-while. These statements create what we commonly call loops. As you probably know, a loop repeatedly executes the same set of instructions until a termination condition is met.

while

The while loop is Java’s most fundamental looping statement. It repeats a statement or block while its controlling expression is true. Here is its general form:

 

while(condition) {

// body of loop

}

 

The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated. Here is a while loop that counts down from 10, printing exactly ten lines of “tick”:

 

// Demonstrate the while loop.

class While {

public static void main(String args[]) {

int n = 10;

while(n > 0) {

System.out.println(“tick ” + n);

n–;

}

}

}

When you run this program, it will “tick” ten times:

tick 10

tick 9

tick 8

tick 7

tick 6

tick 5

tick 4

tick 3

tick 2

tick 1

 

Since the while loop evaluates its conditional expression at the top of the loop, the body of the loop will not execute even once if the condition is false to begin with. For example, in the following fragment, the call to println( ) is never executed:

 

int a = 10, b = 20;

while(a > b)

System.out.println(“This will not be displayed”);

 

The body of the while can be empty. This is because a null statement one that consists only of a semicolon is syntactically valid in Java. For example, consider the following program:

 

// The target of a loop can be empty.

class NoBody {

public static void main(String args[]) {

int i, j;

i = 100;

j = 200;

// find midpoint between i and j

while(++i < –j) ; // no body in this loop

System.out.println(“Midpoint is ” + i);

}

}

 

This program finds the midpoint between i and j. It generates the following output:

Midpoint is 150

 

Here is how the while loop works. The value of i is incremented, and the value of j is decremented. These values are then compared with one another. If the new value of i is still less than the new value of j, then the loop repeats. If i is equal to or greater than j, the loop stops. Upon exit from the loop, i will hold a value that is midway between the original values of i and j.

do-while

As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the loop rather than at the beginning. Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is

 

do {

// body of loop

} while (condition);

 

Each iteration of the do-while loop first executes the body of the loop and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a Boolean expression. Here is a reworked version of the “tick” program that demonstrates the dowhile loop. It generates the same output as before.

 

// Demonstrate the do-while loop.

class DoWhile {

public static void main(String args[]) {

int n = 10;

do {

System.out.println(“tick ” + n);

n–;

} while(n > 0);

}

}

 

The loop in the preceding program, while technically correct, can be written more efficiently as follows:

do {

System.out.println(“tick ” + n);

} while(–n > 0);

 

In this example, the expression (– –n > 0) combines the decrement of n and the test for zero into one expression. First, the – –n statement executes, decrementing n and returning the new value of n. This value is then compared with zero. If it is greater than zero, the loop continues; otherwise it terminates. The do-while loop is especially useful when you process a menu selection, because you will usually want the body of a menu loop to execute at least once. Consider the following program which implements a very simple help system for Java’s selection and iteration statements:

 

// Using a do-while to process a menu selection

class Menu {

public static void main(String args[])

throws java.io.IOException {

char choice;

do {

System.out.println(“Help on:”);

System.out.println(” 1. if”);

System.out.println(” 2. switch”);

System.out.println(” 3. while”);

System.out.println(” 4. do-while”);

System.out.println(” 5. for\n”);

System.out.println(“Choose one:”);

choice = (char) System.in.read();

} while( choice < ‘1’ || choice > ‘5’);

System.out.println(“\n”);

switch(choice) {

case ‘1’:

System.out.println(“The if:\n”);

System.out.println(“if(condition) statement;”);

System.out.println(“else statement;”);

break;

case ‘2’:

System.out.println(“The switch:\n”);

System.out.println(“switch(expression) {“);

System.out.println(” case constant:”);

System.out.println(” statement sequence”);

System.out.println(” break;”);

System.out.println(” // …”);

System.out.println(“}”);

break;

case ‘3’:

System.out.println(“The while:\n”);

System.out.println(“while(condition) statement;”);

break;

case ‘4’:

System.out.println(“The do-while:\n”);

System.out.println(“do {“);

System.out.println(” statement;”);

System.out.println(“} while (condition);”);

break;

case ‘5’:

System.out.println(“The for:\n”);

System.out.print(“for(init; condition; iteration)”);

System.out.println(” statement;”);

break;

}

}

}

Here is a sample run produced by this program:

Help on:

  1. if
  2. switch
  3. while
  4. do-while
  5. for

Choose one:

4

The do-while:

do {

statement;

} while (condition);

 

In the program, the do-while loop is used to verify that the user has entered a valid choice. If not, then the user is reprompted. Since the menu must be displayed at least once, the do-while is the perfect loop to accomplish this. A few other points about this example: Notice that characters are read from the keyboard by calling System.in.read( ). This is one of Java’s console input functions. It reads characters from standard input returned as integers, which is why the return value was cast to char. By default, standard input is line buffered, so you must press ENTER before any characters that you type will be sent to your program. One other point: Because System.in.read( ) is being used, the program must specify the throws java.io.IOException clause. This line is necessary to handle input errors.

for

the for loop is a powerful and flexible loop. Here is the general form of the for statement:

 

for(initialization; condition; iteration) {

// body

}

If only one statement is being repeated, there is no need for the curly braces. The for loop operates as follows. When the loop first starts, the initialization portion of the loop is executed. Generally, this is an expression that sets the value of the loop control variable, which acts as a counter that controls the loop. It is important to understand that the initialization expression is only executed once. Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control variable against a target value. If this expression is true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable. The loop then iterates, first evaluating the conditional expression, then executing the body of the loop, and then executing the iteration expression with each pass. This process repeats until the controlling expression is false. Here is a version of the “tick” program that uses a for loop:

 

// Demonstrate the for loop.

class ForTick {

public static void main(String args[]) {

int n;

for(n=10; n>0; n–)

System.out.println(“tick ” + n);

}

}

 

Declaring Loop Control Variables Inside the for Loop

Often the variable that controls a for loop is only needed for the purposes of the loop and is not used elsewhere. When this is the case, it is possible to declare the variable inside the initialization portion of the for. For example, here is the preceding program recoded so that the loop control variable n is declared as an int inside the for:

 

// Declare a loop control variable inside the for.

class ForTick {

public static void main(String args[]) {

// here, n is declared inside of the for loop

for(int n=10; n>0; n–)

System.out.println(“tick ” + n);

}

}

 

When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. That is, the scope of the variable is limited to the for loop. Outside the for loop, the variable will cease to exist. If you need to use the loop control variable elsewhere in your program, you will not be able to declare it inside the for loop. When the loop control variable will not be needed elsewhere, most Java programmers declare it inside the for. For example, here is a simple program that tests for prime numbers. Notice that the loop control variable, i, is declared inside the for since it is not needed elsewhere.

 

// Test for primes.

class FindPrime {

public static void main(String args[]) {

int num;

boolean isPrime = true;

num = 14;

for(int i=2; i <= num/2; i++) {

if((num % i) == 0) {

isPrime = false;

break;

}

}

if(isPrime) System.out.println(“Prime”);

else System.out.println(“Not Prime”);

}

}

 

Using the Comma

There will be times when you will want to include more than one statement in the initialization and iteration portions of the for loop. For example, consider the loop in the following program:

 

class Sample {

public static void main(String args[]) {

int a, b;

b = 4;

for(a=1; a<b; a++) {

System.out.println(“a = ” + a);

System.out.println(“b = ” + b);

b–;

}

}

}

As you can see, the loop is controlled by the interaction of two variables. Since the loop is governed by two variables, it would be useful if both could be included in the for statement, itself, instead of b being handled manually. To allow two or more variables to control a for loop, Java permits you to include multiple statements in both the initialization and iteration portions of the for. Each statement is separated from the next by a comma. Using the comma, the preceding for loop can be more efficiently coded as shown here:

 

// Using the comma.

class Comma {

public static void main(String args[]) {

int a, b;

for(a=1, b=4; a<b; a++, b–) {

System.out.println(“a = ” + a);

System.out.println(“b = ” + b);

}

}

}

 

In this example, the initialization portion sets the values of both a and b. The two comma-separated statements in the iteration portion are executed each time the loop repeats. The program generates the following output:

a = 1

b = 4

a = 2

b = 3

Nested Loops

Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. For example, here is a program that nests for loops:

 

// Loops may be nested.

class Nested {

public static void main(String args[]) {

int i, j;

for(i=0; i<10; i++) {

for(j=i; j<10; j++)

System.out.print(“.”);

System.out.println();

}

}

}

 

The output produced by this program is shown here:

……….

………

……..

…….

……

…..

….

..

.

 

Jump Statements

Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program.

Using break

In Java, the break statement has three uses. First, as you have seen, it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as a form of goto.

Using break to Exit a Loop

By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement following the loop. Here is a simple example:

 

// Using break to exit a loop.

class BreakLoop {

public static void main(String args[]) {

for(int i=0; i<100; i++) {

if(i == 10) break; // terminate loop if i is 10

System.out.println(“i: ” + i);

}

System.out.println(“Loop complete.”);

}

}

 

This program generates the following output:

i: 0

i: 1

i: 2

i: 3

i: 4

i: 5

i: 6

i: 7

i: 8

i: 9

Loop complete.

 

As you can see, although the for loop is designed to run from 0 to 99, the break statement causes it to terminate early, when i equals 10. The break statement can be used with any of Java’s loops. For example, here is the preceding program coded by use of a while loop. The output from this program is the same as just shown.

 

// Using break to exit a while loop.

class BreakLoop2 {

public static void main(String args[]) {

int i = 0;

while(i < 100) {

if(i == 10) break; // terminate loop if i is 10

System.out.println(“i: ” + i);

i++;

}

System.out.println(“Loop complete.”);

}

}

 

When used inside a set of nested loops, the break statement will only break out of the innermost loop. For example:

// Using break with nested loops.

class BreakLoop3 {

public static void main(String args[]) {

for(int i=0; i<3; i++) {

System.out.print(“Pass ” + i + “: “);

for(int j=0; j<100; j++) {

if(j == 10) break; // terminate loop if j is 10

System.out.print(j + ” “);

}

System.out.println();

}

System.out.println(“Loops complete.”);

}

}

This program generates the following output:

Pass 0: 0 1 2 3 4 5 6 7 8 9

Pass 1: 0 1 2 3 4 5 6 7 8 9

Pass 2: 0 1 2 3 4 5 6 7 8 9

Loops complete.

 

As you can see, the break statement in the inner loop only causes termination of that loop. The outer loop is unaffected. Here are two other points to remember about break. First, more than one break statement may appear in a loop. Second, the break that terminates a switch statement affects only that switch statement and not any enclosing loops.  

Using break as a Form of Goto

In addition to its uses with the switch statement and loops, the break statement can also be employed by itself to provide a form of the goto statement. Java does not have a goto statement, because it provides a way to branch in an unstructured manner. There are, however, a few places where the goto is a valuable construct for flow control. For example, the goto can be useful when you are exiting from a deeply nested set of loops. To handle such situations, Java defines an expanded form of the break statement. By using this form of break, you can break out of one or more blocks of code. These blocks need not be part of a loop or a switch. They can be any block. Further, you can specify precisely where execution will resume, because this form of break works with a label. As you will see, break gives you the benefits of a goto without its problems. The general form of the labeled break statement is shown here:

 

break label;

 

Here, label is the name of a label that identifies a block of code. When this form of break executes, control is transferred out of the named block of code. The labeled block of code must enclose the break statement, but it does not need to be the immediately enclosing block. This means that you can use a labeled break statement to exit from a set of nested blocks. But you cannot use break to transfer control to a block of code that does not enclose the break statement. To name a block, put a label at the start of it. A label is any valid Java identifier followed by a colon. Once you have labeled a block, you can then use this label as the target of a break statement. Doing so causes execution to resume at the end of the labeled block. For example, the following program shows three nested blocks, each with its own label. The break statement causes execution to jump forward, past the end of the block labeled second, skipping the two println( ) statements.

 

// Using break as a civilized form of goto.

class Break {

public static void main(String args[]) {

boolean t = true;

first: {

second: {

third: {

System.out.println(“Before the break.”);

if(t) break second; // break out of second block

System.out.println(“This won’t execute”);

}

System.out.println(“This won’t execute”);

}

System.out.println(“This is after second block.”);

}

}

}

Running this program generates the following output:

Before the break.

This is after second block.

 

One of the most common uses for a labeled break statement is to exit from nested loops. For example, in the following program, the outer loop executes only once:

 

// Using break to exit from nested loops

class BreakLoop4 {

public static void main(String args[]) {

outer: for(int i=0; i<3; i++) {

System.out.print(“Pass ” + i + “: “);

for(int j=0; j<100; j++) {

if(j == 10) break outer; // exit both loops

System.out.print(j + ” “);

}

System.out.println(“This will not print”);

}

System.out.println(“Loops complete.”);

}

}

This program generates the following output:

Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

 

As you can see, when the inner loop breaks to the outer loop, both loops have been terminated. Keep in mind that you cannot break to any label which is not defined for an enclosing block. For example, the following program is invalid and will not compile:

 

// This program contains an error.

class BreakErr {

public static void main(String args[]) {

one: for(int i=0; i<3; i++) {

System.out.print(“Pass ” + i + “: “);

}

for(int j=0; j<100; j++) {

if(j == 10) break one; // WRONG

System.out.print(j + ” “);

}

}

}

 

Since the loop labeled one does not enclose the break statement, it is not possible to transfer control to that block.

Using continue

Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop, but stop processing the remainder of the code in its body for this particular iteration. The continue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. For all three loops, any intermediate code is bypassed. Here is an example program that uses continue to cause two numbers to be printed on each line:

 

// Demonstrate continue.

class Continue {

public static void main(String args[]) {

for(int i=0; i<10; i++) {

System.out.print(i + ” “);

if (i%2 == 0) continue;

System.out.println(“”);

}

}

}

 

This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline. Here is the output from this program:

0 1

2 3

4 5

6 7

8 9

 

As with the break statement, continue may specify a label to describe which enclosing loop to continue. Here is an example program that uses continue to print a triangular multiplication table for 0 through 9.

 

// Using continue with a label.

class ContinueLabel {

public static void main(String args[]) {

outer: for (int i=0; i<10; i++) {

for(int j=0; j<10; j++) {

if(j > i) {

System.out.println();

continue outer;

}

System.out.print(” ” + (i * j));

}

}

System.out.println();

}

}

 

The continue statement in this example terminates the loop counting j and continues with the next iteration of the loop counting i. Here is the output of this program:

0

0 1

0 2 4

0 3 6 9

0 4 8 12 16

0 5 10 15 20 25

0 6 12 18 24 30 36

0 7 14 21 28 35 42 49

0 8 16 24 32 40 48 56 64

0 9 18 27 36 45 54 63 72 81

return

The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method. As such, it is categorized as a jump statement. At any time in a method the return statement can be used to cause execution to branch back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed. The following example illustrates this point. Here, return causes execution to return to the Java run-time system, since it is the run-time system that calls main( ).

 

// Demonstrate return.

class Return {

public static void main(String args[]) {

boolean t = true;

System.out.println(“Before the return.”);

if(t) return; // return to caller

System.out.println(“This won’t execute.”);

}

}

The output from this program is shown here:

Before the return.

 

As you can see, the final println( ) statement is not executed. As soon as return is executed, control passes back to the caller. the if statement is used here to trick the compiler for the sake of this demonstration.