Menu
Topics Index
...
`


Control Statements > Jump Statements >
Siva Nookala - 12 Apr 2016
return statement is used to explicitly return from a method. It causes the program control to transfer back to the caller of the method.

return can be used to return from any part of the method code.
Return Statement
class ReturnStatement
{
    public static void main(String arg[])
    {
        boolean t = true;
        
        System.out.println("Before the return"); // LINE A
        
        if(t) return; // return to caller
        
        System.out.println("This won't execute"); // LINE B    
    }
}
OUTPUT

Before the return

DESCRIPTION

After LINE A is executed, the return statement is called which will be prevent LINE B from executing. That is why we see only Before the return in the output.
We can not call return statement in the middle of method body with out having a if condition. If there is no if condition, return will be always called, so LINE B will never execute. The java compiler detects this scenario and shows a compilation error unreachable statement. To prevent that error we put an if condition, but ensured that it will be always true.

THINGS TO TRY
  • Change the value of variable b from true to false and see that both Before the return and This won't execute are printed since the return is statement is not called.
  • Replace the statement if(t) return; with return; to see the compilation error unreachable statement

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App