Home Topic 4

Methods - Part 2 - Focus on the "Return" Part


 2 package methodspackage;
 4 public class Volcanos {
 5     public static void main(String[] args) {
 6         System.out.println(volcano("Eyja", 3000));
 7         System.out.println(volcano("Mount Vesuvius", 4000));
 8     }
 9     public static String volcano(String name, int height){
10         String s = "not set yet";
11         if(name.equals("Eyja")){
12             s = name + ": This Icelandic volcano is " + height + " meters high.";
13         }
14         else if(name.equals("Mount Vesuvius")){
15             s = name + ": This ancient Italian volcano was " + height + " meters high before it collapsed.";
16         }
17         else{
18             s = "Neither Eyja nor Mount Vesuvius were sent as arguments"
19         }			  
20         return s;
21     }
23 } 

The methods that we looked at last time had the word void in their header line. This viod meant that they were void of any return value. To be void of something means to be lacking it.

A return value is a value that is "sent back" by the method to the place in the program where the method was called. So when a method which has a return value is called, not only does the flow of control go to that method until the method is complete, but also, a value is returned. And the return value essentially takes the place of the method call where the method call occurs. Or we can say that the method call evaluates to the return value.

So in the above example, you would normally expect a System.out.println method to take in a String in double quotes. In the example, though, what it takes in is a call to the volcano method. But that's Ok since the volcano method evaluates to a String - it is a String, which is returned.


Requirements For Proper Return Method Use

Two or three things are required to properly implement a "return" method. Firstly, the return type must be in the method header (in the place of where void would be).
For example: public static int method2()

Secondly, the last line (or possible lines**) of the method must be a return statement, which returns the same type as stipulated in the method header.
For example: return 3;

**Note that it is possible for there to be multiple return statements in one method, if there is a conditional block where the return(s) should be. Keep in mind that only one of the blocks will ever be entered, and each of them may require a return line at the end of the block.

if(grade > 90){
    return "A";
}else if(grade > 80){
    return "B";
}else if(grade > 70){
    return "C";

The other thing to be careful about is that you properly call the method so that the type that it returns makes sense, when that value takes the place of the method call.


Note finally that whether or not a method takes in any parameters does not influence whether or not there is a return value. Parameters (or not) and return values (or not) are independent of each other.


Link to Methods Notes Part 3