Friday, 17 January 2014

JUMP STATEMENTS OR BRANCHING STATEMENTS:return

Using return statement


return:


The return statement is used to explicitly return from a method. The return statement is used to explicitly return from the method . That is, that is it causes program control to transfer back to the caller of the method.
.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.

Let’s look at syntax of return statement:

return;

Example for simple return  statement

// Demonstrate return .
class Returnex
{
public static void main(String args[])
{
boolean p=true;
system.out.println("before the return.");
if(p) return; //return to caller
system.out.println(" this won't execute.");
}
}

This would produce the following results

  before the return

As you can see, the final println() staement is not excecuted. as soon as return is executed,control passes back to the caller.In this program ,the if(t) statement 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