Returning from a Method
In general, there are two conditions that cause a method to return—first, as the range( ) method in the preceding example shows, when the method’s closing curly brace is encountered. The second is when a return statement is executed. There are two forms of return—one for use in void methods (those that do not return a value) and one for returning values. The first form is examined here. The next section explains how to return values.
In a void method, you can cause the immediate termination of a method by using this form of return:
return;
When this statement executes, program control returns to the caller, skipping any remaining code in the method. For example, consider this method:
Here, the for loop will only run from ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access