ptarimagan traverse
Students at North Campus, Fa17 Wed 6-9pm section explore method calls with return types in a human-modeling activity.

Methods 2: Methods with return types

Parent Component: Chunk 2 - 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.

preparation

This module is the second in our language structures chunk. If you have not digested settings Chunk 2, Module 1: Simple Methods, pause and do so before attemtping this module.

objectives

  1. Write methods without return types from English descriptions
  2. Write methods that take parameters and returns primitive types to the calling method
  3. Usefully capture and process data passed back from methods

time considerations

As a core module in your Java learning, plan to devote about 4 hours to this module. Best to spread that out over two sessions, or so. Don't forget to pause and study your resources!

resources

Java: A Beginner's Guide (6th ed): Methods are covered in Chapter 4, pages 103-124. Stop at "Constructors" which delves into Object-oriented Java which we'll explore soon.

Oracle online tutorial on methods provides essential explanations of these core concepts

contents

extensionCore Concept 1: Summary of three method structures
extensionCore Concept 2: Writing Type III methods which take input parameters and return values
extensionCore Concept 3: Calling Type-III methods
motorcycleExercise 1: Adding a cylinder volume calculation method

extensionCore Concept 4: Writing simple algorithms
motorcycleExercise 2: Adding your favorite shape computation method

extensionCore Concept 5: First look at the Java API
motorcycleExercise 3: Tinkering with methods on String objects

buildMini-Project: Building a unit Converter

"submitting"

  1. Code up your mini-project, test it, and comment your code. Please make a note of any outside resources you used for any part of your code by including a link or attribution in your comments.
  2. Upload your file to your personal GitHub account.
  3. Make an entry in our java submission index, including a link to your file on GitHub.

extensionCore Concept 1: Summary of three method structures

We can categorize methods into three types summarized in the feature box below. Chunk 1, Module 1 explored types I: Simple, no-argument methods and type II methods: those which require an input value but return nothing. This module introduces type III methods.

type I
methods

The simplest of all possible methods: a named block of code that "just does its thing" when called, requiring no inputs and returning no values.

type II methods

These methods require one or more pieces of data to carry out its task. We specify what the method requires in its declaration. When we pass this data into the method during execution, we specify the values to send with arguments to these methods.

type III methods

"Fully-baked" methods which take in one or more values and return a computed value of a declared type. A good chunk of all methods we use in Java are type III methods since receiving values from a method is a very useful process.

arrow_upward back up to contents


extensionCore Concept 2: Writing Type III methods which take input parameters and return values

arrow_upward back up to contents


extensionCore Concept 3: Calling Type III methods

arrow_upward back up to contents


motorcycleExercise 1: Adding a cylinder volume calculation method

arrow_upward back up to contents


extensionCore Concept 4: Writing simple algorithms

arrow_upward back up to contents


motorcycleExercise 2: Adding your favorite shape computation method

arrow_upward back up to contents


extensionCore Concept 5: First look at the Java API

arrow_upward back up to contents


motorcycleExercise 3: Tinkering with methods on String objects

arrow_upward back up to contents


buildMini-Project: Building a unit Converter

This project asks that you assemble your learning from the above core concepts and exercises into a working program structured with method calls and proper flow of data to and from those methods.

As usual, we should always try to code to a specification--even if that specification is one we make for ourselves. We must organize our logic around some specific goal, and revise that goal if necessary.

program overview

Create a handy unit conversion program which can transform unit quantities entered by the user into a chosen unit type (e.g. knots into miles per hour).

requirement 1

Choose three pairs of units that you might actually want to convert between in your life or work. They can be related to a single type of measurement (speed, volume, weight, etc.) or be drawn from several types of measurement.

Accurately compute the conversions by hand using correct formulas. This unit conversion reference might be handy. The inter-webs can supply many others.

requirement 2

Create an appropriately named class composed of a main method which coordinates the flow of data to and from methods which implement data cleaning and conversion operations.

Create a separate method for each of your three conversions. Name your methods with action words (e.g. convertMilesToKm).

Plan your method signatures carefully. Each method should require one or more input parameters and return the final converted value to the caller. Once your methods are in place with proper signatures, you're well on your way.

requirement 3

In the main method, create a very simple user interface which prompts the user for values to convert and displays the converted values. Be sure to tell the user the unit of measurement to enter, and what will be computed.

The unit conversion algorithm writing and method calling is a substantial project by itself, so your user interface can be bare bones. It would be handy to program a switch statement inside a while loop to allow the user to choose a converter to execute, but this is not necessary for this exercise.

Sample output

The program generating this output meets the above specifications. Remember! You can always add features above requirements in this class, so don't limit yourself by sample output.

Suggestions & tips

Extension ideas

arrow_upward back up to contents


Core Concept 1: Writing methods that yield return value

Methods are named blocks of code that do something specific when called. Some methods do their task without any data needing to be passed by the caller. and given the requried inputs. We can think of any method in Java as a function with inputs and outputs. In fact, the notion of a mathematical function is implemented in Java as a method. (Java just uses the name method instead of function.)

In this core concept section, we'll be creating methods that all compute some sort of geometric value based on the inputted values. The first method we'll write calculates the volume of a cube when passed in the length of any given side. We can model the method like this:

method structure

Setting up our GometricShapes class

Create a skeleton of our class which we'll add meat to during this module. Use these steps:

  1. Create a new package called week8_methods2
  2. Inside this package, create a class called GeometricShapes
  3. Code up a main method with the proper method signature

Coding up calcVolumeOfCube

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

Listing 1: code for calcVolumeOfCube
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!

Calling our method calcVolumeOfCube and 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

Dissecting calcVolumeOfCube

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.

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

Executing our new method

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.

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:

Preparing for a return type:

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.


Exercise 1: Creating a second method called calcVolumeOfCylinder

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

Exercise 2: Trapezoids!

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


Group Exercise: 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.

back to top