Why is it that you only sometimes need to put return after the method in order for it to go back to the main when at other times it just calls it without this?
Return after the method
You must be signed in to leave a comment
14 December 2020, 20:46
The return keyword can be used in any method to return the execution of code back to where it was called from. When used in the main method (the one that is run when the program is started), if a return statement is reached then the program would end. Typically that would be used behind a logic gate to end a program if the requirements for the continuation of the program are not met. All methods are declared with a return value, and if there is not supposed to be a return value then you have to still specifically state that the "return value" is void. When a method is not void that means it must reach a return statement that returns a valid value, otherwise the code is illegal and will not compile. Say if you are programming a method that has a return value that is an int, the method must return an int through all the possible code paths and logic gates, and would be illegal to not do so. So, here are a few brief examples: #1 this is a method that has a return value of int (declared right after the public modifier). Therefore it MUST return an int as shown below.It cant do something like this: because it declares an int as the return value but no return statement is reached that returns an int #2 Here is an example of a "void" method. You can add a return statement if you want, but it is not required. It will execute until either it completes or reaches a return statement. Both cases will go back to where it was called.
14 December 2020, 20:50
#3 just a little bit more. If the method has a return value then all code paths much reach a valid return statement:Here the method has a specified return value of String. Therefore it HAS to return a string. It is illegal for any code path to exist that does not return a String. In this example it only returns a String if today is Monday. The compiler detects that not all code paths have a valid return value and the code would not compile.