The last of the control operators is
The operator
return
. It is used to perform an explicit return from a method. That is, it again transfers control to the object that called this method. As such, this operator is classified as a transition operator. Although a full description of the operator return
will have to wait until we discuss the methods in Chapter 6, let's take a quick look at its features. return
can be used anywhere in a method to return control to the object that called the method. Thus, the statement return
immediately stops executing the method it is in. The following example illustrates this. In this case, the return statement causes control to return to the Java runtime system, since it is the one that calls the main ()
.
// Демонстрация использования оператора return.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("До выполнения возврата.");
if (t) return; // возврат к вызывающему an objectу
System.out.println("Этот оператор выполняться не будет.");
}
}
The output of this program looks like:
До выполнения возврата.
As you can see, the final statement println ()
is not executed. Immediately after the statement is executed, return
the program returns control to the calling object. And the last nuance: in the above program, the use of the operator if (t)
is mandatory. Without it, the Java compiler would signal an "unreachable code" error because it would figure out that the last statement would println ()
never be executed. To avoid this error, the demo had to fool the compiler with the if
. Link to original source: Return statement
What else to read: |
---|
GO TO FULL VERSION