Topics Index

Return Statement - Java Example Program

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    

Before the return


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.

  • 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

© meritcampus 2019

All Rights Reserved.

Open In App