Logout

Methods - Part 2 - The "Return" Part

 

 1 
 2 package methodspackage;
 3 
 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     }
22 
23 } 
 

The methods that we looked at last time had the word void in their titles. 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 goes 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.

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 - since it is a String which is returned.

So whereever you see volcano("String", int) in the program, you can replace it with one of the three values that the variable s can take.

 

Requirements For Proper Return Method Use

Two 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 of the method must be a return statement, which returns the same type as stipulated in the method header.
For example: return 3;

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 (like we learned about last time) 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