Ask a Teacher

what is the use of return statements in a java programming?

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. A brief look at return is presented here.
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.
One last point: In the preceding program, the if(t) statement is
necessary. Without it, the Java compiler would flag an "unreachable
code" error, because the compiler would know that the last println(
)statement would never be executed. To prevent this error, the if
statement is used here to trick the compiler for the sake of this

comments powered by Disqus