Sunday, September 27, 2015

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. 

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 statement.
class WLReturn
{
public static void main(String args[])
{
int i=10,j=2;
System.out.println("Before Return Statement");
return;  // return to caller
System.out.println("After Return Statement");
}
}
Type following command in command prompt
javac WLReturn.java
WLReturn.java:8: error: unreachable statement
                System.out.println("After Return Statement");
                ^
1 error
// Demonstrate return statement.
class WLReturn
{
public static void main(String args[])
{
int i=10,j=2;
System.out.println("Before Return Statement");
if(i%j == 0)
return; // return to caller
System.out.println("After Return Statement");
}
}
Type following command in command prompt
javac WLReturn.java
java WLReturn
Before Return Statement
As you can see the final println() statement is not executed. As soon as return is executed control passes back to the caller.

In the preceding program, the if(i%j == 0) 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 demonstration.

No comments:

Post a Comment

If you have any query please comment here, Will get back to you :)