JavaRush /Java Blog /Random EN /return statement
articles
Level 15

return statement

Published in the Random EN group
The last of the control operators is 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 returnwill have to wait until we discuss the methods in Chapter 6, let's take a quick look at its features. Operator return - 1The operator returncan be used anywhere in a method to return control to the object that called the method. Thus, the statement returnimmediately 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, returnthe 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:

Return Statement in Java

Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION