Module: Methods with return types

Parent Component: Language Structures

Methods become much more useful when they can receive information from the calling method, do some operations on them, and then pass a computed value back for the calling method to do with as it pleases.

Jump to a section

Learning Objectives
Core Concepts
Resources and reference documents
Module Preparation Exercises
Exercise 1:
Exercise 2:
Mini Project:
Extension Exercises

Learning Objectives

  1. Write methods without return types from English descriptions
  2. Model the behavior of methods with return types through human interaction
  3. Write methods that take parameters and returns primitive types to the calling method
  4. Usefully capture and process data passed back from methods

back to top

External Resources

Oracle online tutorial on methods

Exercise 1: Warm up with simple methods

Exercise type: Test yourself

Implement the following steps in Java. Check your work as needed--don't peek too soon!

  1. Clear your Sandbox class of all methods except main(). Erase any statements.
  2. Write a method called simulateCarStarting() that accepts a String as a parameter. It should have the modifiers "public static void" before the method name.
  3. Inside simulateCarStarting() print a line to the console that says: "Simulate sound of car starting"
  4. After this println() call, print out the String the user passed into the method, and add an exclamation point after it.
  5. Now write a call to this method in main() and pass in the sound "Vroom."
  6. Test your code to show that you can call the method, which does the printing using the parameter passed int.

back to top

Exercise 2: Methods practice with math

Exercise type: Check yourself

Follow these steps to practice a method construction

  1. Clear your sandbox so only a main() method is inside your class.
  2. Create a method called doBasicMath. This should have the following in its signature: public static void. This method should accept two int values as parameters.
  3. Inside the method, create a new integer with a name of your choosing. Take the second number inputted into the method and multiply it by 2. Then add it to the first number. Store this result in the variable you just created.
  4. Print out to the console the two numbers that were passed into the method, and print out the result of this basic math.
  5. Now up in main, call the method doBasicMath and pass down the integer values of 10 and 20. Run the program to verify that the output is 50.

back to top

Exercise 3: Human modeling of method and call interactions

Exercise type: Get up and move!

We are going to model the interaction between a calling line of code and the method it is calling. In other words, we're modeling the contract between the method author and the method caller. Do the following:

Human Method Modeling (HMM) parameter, return value, and method description cards-- PDF

Human Method Modeling (HMM) parameter, return value, and method description cards-- Editable *.odt file (open document text format)

  1. Find a mathematical equation that is of interest to you. This could be from geometry, or science, or a conversion between units, such as the English and the metric systems.
  2. Write out your formula in a method diagram. What values do you need to receive from the user in order to carry out your calculation? What will you give back? What units are at work here? Map this out.
  3. Make yourself a sheet of paper that documents your method with the method signature (the return type, name, and parameters), a description of what your method does, and what it returns. Print off two copies of this--one for you as the method and one for the calling line of code.
  4. During the exercise, we'll have students model the user, the Java Virtual Machine, and the method that receives parameters and send back return values.

Exercise 4: Writing methods that send data back as return values

Exercise type: Code-along with Eric

Our last addition to our understanding of methods involves calling and writing methods that pass a value back to the line of code that called the method. This is called a method that produces a return value. Our example will involve a set of methods that compute some sort of geometric value, such as the volume of a cube. This is a nice case study since the formulas that we're using require one or two variables and return a single variable--just the setup that Java's methods are designed to handle. If our method is called calcVolumeOfCube(), we can diagram the relationship between the calling line of code and the method it is calling as follows:

Java diagram of a method that requires an argument and returns a value

The signature of calcVolumeOfCube() contains the word double directly before the method name, whereas our previous method signatures all contained the word void. This means our method sends a value of type double back to the calling line of code. To add the functionality of the method returning a value, we replace the word void with the TYPE of data that will be sent back. This can by any primitive or object type. In our example, we are writing methods that compute a numeric value using a geometric formula and they will pass the computed value back to the calling method as a type double.

calculateVolumeOfCube also requires the length of each side of the cube of type double as a parameter--and we know how to do this from exercise 2. It also returns the volume of the cube as a type double to the line of code that called the method.

Before we start coding, let's envision what the output of our program can look like:

java output of a method that computes the volume of a cube with a given side length

The user enters chooses a cube length, inputs it to the console. This value is passed to calculateVolumeOfCube as an argument to the method call. The method does the geometric math and sends back the volume of the cube. We stored that volume somewhere and printed it out to the console.

We can start coding now that we have the structure and objective in our heads. Here are the guts of calculateVolumeOfCube:

Sample code of a method that takes a parameter to calculate the area of a cube and returns the volume as a double value to the calling code.

Aside from including a return type in the method signature, the key difference between this method's guts and our previous methods is that calculateVolumeOfCube contains a special statement that starts with the java keyword return and includes a value of the type the method returns to the calling method--in our case, double. This is enforced by the compiler--if you have a return type in the signature, you must have a return statement somewhere in your method. Try taking out the return statement and read the error the compiler gives us!

Preparing for a return type:

When we call the calculateVolumeOfCube with an input parameter of type double, we must prepare for the method to give us back a double that is the volume of the cube with the side length we sent. We usually deal with the return type by storing it in a variable, as shown below:

calling a method with an input parameter that returns a double value

Following this line of code we now have a variable called returnedVolume which we can then use however we'd like. In this case of this sample program, we are just printing the value out to the console along with the input side length:

A complete java code cycle of calling a method with a return value and printing that value to the console

Check out the completed "seed" code for this class that contains one method and a call to that one method.

Continue Activity 1 on your own:

Move any code that's currently in your playground into a class called GeometricShapes. Create a main() method just as we have been using. Now, with our method structure in mind, let's work in the code to gather the user input. Here's the lines for collecting a double representing the length of the side of the cube:

code to gather user input for method calling practice

Make sure that calculateVolumeOfCube() is written inside the class but after main's closing }. Run your code and check that it works as expected.

Design and add a second method called calcVolumeOfCylinder that requires two parameters, a double for the radius of the cylinder and a double for the height. Since this isn't a math class, here's the guts (guts only!) of the method such that you don't have to worry about coding that algorithm yet:

calculating the volume of a cylinder in java

Note that this line of code does not complete the method's guts: we still need to return the volume of the cylinder to the calling method with a return statement. Add that now.

Back in main(), gather a height and base radius from the user, then call calculateVolumeOfCube(). Test your output against this sample output:

Output of java program which calculates the volume of a cube and volume of a cylinder

Extension activity 2: Adding a trapezoid area method

In the same pattern as our previous two math methods, create a method called calcAreaOfTrapezoid() that takes three parameters to calculate the area of any given trapezoid: the length of the two bases and the height. So your method will take three input parameters and return the area of the trapezoid. The algorithm for calculating the area looks like this:

Java code for calculating the area of a trapezoid

Finish coding this method. Then go back to main() and create a process for asking the user for each of the three parameters and storing the return value the method provides.

Check out the completed code if you need to--don't peek too early thought!

back to top

Module mini-project

Choose an extension activity from exercises 1,2, or 3 above. Each activity contains sample seed and final code on GitHub for your reference. Once you're done making a solid working class with method calls, complete the hamburger.

back to top