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. It belongs to jump statement.
At any time in a method, the return statement can be used to control back to caller of the method. Thus, the return statement immediately terminates the method in which it is executed.
Example:
// Demonstrate return statement class ReturnStatement { public static void main(String args[]) { boolean t = true; System.out.println("Before the return statement."); if (t) return; // return to caller System.out.println("This won't execute."); } }
Output:
Before the return statement.
In the above program, return statement used inside the main() method. Java run-time system calls the main method, so return causes execution to return to the Java run-time system.
As you can see, the final println( ) statement is not executed. As soon as return is executed, control passes back to the caller.
Important point: 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 demonstration.
factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
ReplyDeletefactorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.
factorial hundred In the last few days, the “factorial of 100” is one of the top subjects and a lot of maths geeks compute it using voice assistants such as Alexa, Shiri, etc.