Module: Language Structures 1 - Calling Methods

Parent Component: Java Language Structures

Methods are blocks of code that have a name and can be executed by other code simply by "calling" the method with that name and passing to it whatever input parameters its contract requires. Methods can return a value to the calling method, which can then be used for further calculations and manipulations.

A method should be responsible for carrying out one specific task, and it should do so correctly and consistently. This is known as a modular approach to programming: separate our code into distinct little chunks that can be programmed and tested by themselves before being assembled into a larger application.

Jump to a section

Module "hamburger" guide
Learning Objectives
Methods Core Concepts
Resources and reference documents
Module Preparation Exercises
Exercise 1: Methods without parameters or return values
Exercise 2: Methods with input parameters
Exercise 3: Methods with input parameters and return types
Mini Project: Extend one of our activities


Module Hamburger Guide

Ask Eric for (or print off) the hamburger guide for this module, review it carefully, and complete its sections as a culminating activity for this module.

When your module is in ship-shape, fold the module page hamburger style and slide all of your module documents inside the fold. Place the whole hamburger into the right pocket of your folder for review.

Language Structure 1 (LS1) Hamburger (*.pdf)

Learning Core 3 Hamburger (open document text *.odt)

back to top


Learning Objectives

  1. Call a method which returns no value and requires no parameters
  2. Call a method which requires input parameters
  3. Store the return value from a method call and use it in a useful way inside the calling method
  4. Extract the "method contract" from a given method signature, diagram that relationship, and implement a call to this method in Java

back to top


Module Core Concepts

We'll explore the concept of methods through the following activity flow. Key points are presented in a series of little chunks designed to build knowledge about methods by calling and writing methods of increasing complexity.

back to top


External Resources

Oracle online tutorial on methods

Book sections from Java: A Beginner's Guide

Methods are covered in Chapter 4, in context of class structure. Not a bad idea to read the chapter, but if time is short, focus on the methods sections starting on page 110 through 119.

back to top


Prep-Work

Activities and readings to do prior to our starting the module in class:

  1. Read the online and/or book tutorials under the Resources section of this page.
  2. Read the Java code for this module on our course's github account.
  3. Try working through exercise 1 below on your own. Just do the work in your Playground (or Sandbox) class--tinker!

back to top


Exercise 1: Calling methods requiring no arguments and returning no values

Exercise type: Code-along with Eric

Methods are blocks of code that have a name and can be executed by other code simply by "calling" the method with that name and passing to it whatever input parameters its contract requires. Methods can return a value to the calling method, which can then be used for further calculations and manipulations.

A method should be responsible for carrying out one specific task, and it should do so correctly and consistently. This is known as a modular approach to programming: separate our code into distinct little chunks that can be programmed and tested by themselves before being assembled into a larger application.

We've seen lots of methods before!

In order to call a method, making it do the job it was written to do, we must have a coded method first. In our case, our method is called openDoor1() and does not require any information to do its job. We simply call it up and say "Go! Do your thing!" and the statements inside that method block are called and program flow returns to where the method was called.

Here's the code for openDoor1:

We call a method by writing the name of the method followed by (parenthesis) that contain a comma-separated list of values that match up with the parameters of the method. Our method, openDoor1() doesn't have any values in its () so we know that when we call this method, we don't have to pass anything down to the method. We just write its name and an empty () and off the method goes.

We tell the user that we're about to call the method, then we call it by writing its name and ending the statement with a semi-colon ; Here's how simple it is to call openDoor1() in code:

We can draw a flow-chart of how the call from our main() method down to openDoor1() looks:

We use the dotted lined arrows to signal that we are just asking the method to execute but aren't passing any values to that method. We'll do that in the next exercise.

You Try Steps:

  1. Write a new method just like openDoor1() but call it openDoor2(). This method is written directly after openDoor1()'s closing curly brace }. Make sure you put the method inside the class's closing } brace but outside openDoor1()'s. The println() statement in this closeDoor2() method can convey any fictitious thing that the door opener should receive.
  2. No go back to main() to call your new method--openDoor2(). Write a call to println() to tell the user that you are about to call openDoor2().
  3. Write an openDoor3() method with a different contents.
  4. Just like we did for openDoor2() write a call to openDoor3() inside main().

You have access to the completed "seed" code for this DoorGame class here to make sure you can get your base class working.

Extension Ideas

Create a class called DoorGame and transfer over any code you worked in in your sandbox into the class body.

You could choose one of these extensions to this class as your module mini-project. Each improvement is marked for relative skill level. Choose an appropriate level for your current skill level.

  1. Extension 1: Use the following code snippet to gather an integer from the user. Get this code running in your class. (Don't forget to import java.util.Scanner after the package name and before you start the class DoorGame!)



    Then write an if()-controlled block that will only call openDoor1() if the user entered the integer 1. Then write two more if()-controlled blocks to check for requests to open door 2 and 3. You can peek at example code here--but don't do so until you've tried to code it using your own skill and other resources, like the Oracle online tutorial on if()-controlled blocks.

    Here is a sample output of this if-controlled behavior:

  2. Extension 2: Use a switch-statement controlled block to select the correct method call based on user input. Review oracle's tutorial on switch statements. For example, if the user types in the number 2, we want the code to execute only a call to openDoor2(). Note that switch() blocks are really just fancy ways of creating chained if()-controlled blocks. Their control statement is based on equality only, and are thus more limited in how they can branch code execution. Read Extension 1 and use the user input code to get that integer from the user.

Check out the completed code for the DoorGame here. Remember to not peek too early--don't let your brain turn to mush!

back to top


Exercise 2: Calling methods that take parameters

Exercise type: Code-along with Eric

Many methods are useful because they can do something interesting with information "passed to the method" when it is called. We could send a String representing a name to a method, for example, which it might use to create a formal greeting. An example of this method is as follows:

greeting method that takes parameters

Notice the method signature of the greet() method. It's labeled public so anybody can call it. Static relates to its position in the Object--we'll learn this soon. void means that the method doesn't pass any information back to the calling line of code, in some other method. What is important is the two String typed variables in the(). This means that whatever code calls this method MUST send the method two values of type String. In our case, the method uses those two names when it assembles a custom greeting String, which it then displays to the console.

The variables greeter and greetee are only available inside the greet() method. They become local variables when the method is called. That's why we have to give them a type in the method signature: String. Whatever is passed down as the first argument (before the , ) is stored in the String type variable greeter. Similarly, whatever String value is passed as the second argument in the method call is stored in greetee.

So, since the method requires two String values, when we call that method, we send two Strings. This is a call to greet in which the names "Helen" and "Esther" are passed as arguments to the greet() method. The term "argument" is a strange one. It has no relationship to human-to-human arguments. An argument is a piece of data that is passed to a method when that method is called.

Java code showing a method call with two parameters passed down to the method

Without those two names passed in, the greet() method wouldn't "know" who to greet, and it's greeting would be generic and less useful. The output of our simple program that uses a greet() method to create a custom greeting is: Java code showing the output of a program that calls a method that requires two Strings to create a custom greeting.

We can show this relationship between the calling line of code and the method it is calling through this digram:

Diagram showing java code in main() calling the greet() method, passing down two Strings as arguments to the parameters in greet()

Your Turn! Follow these steps to continue method parameters

  1. Make sure you have a running greet() method that we created in the exercise overview above. Now, add a new method called generateRandomInteraction(String doer, String receiver). You'll need to complete this method signature by declaring it public and static. Also, remember that a method is just a block of code enclosed in { and }.
  2. Now, write the method generateRandomInteraction. When we write this method, we have access to two new variables, doer and receiver. Use those variables to create a single sentence that uses these two parameters to explain something that the doer did to the receiver. Here's a sample output--Don't copy mine:

    Sample java program output showing the result of calling a method with two string parameters
  3. Now go back to main() and create a call to this method and pass in two Strings--any String values you'd like--as arguments to generateRandomInteraction. When you run the program, the output should look like the output above in that both names passed down to generateRandomInteraction are used in a single string, which that method prints out.

Completed seed" code for TwoNames can be found here.

Extension exercise 1

For this extension, create a third method called convertAndSquish that requires two String arguments and changes those two Strings to all uppercase characters using the toUpperCase() method that can be called "on" any String variable. Convert both of the Strings to upper case and then store them in a new variable without any space between them. Sample output of the finished program is shown below. Note the output of the third method was produced by passing in "Gretchen" and "Gordon", in that order.

The output of a java program that calls a method that takes two string arguments and squishes them together after converting them to capital letters

Check out the completed code for the TwoNames class here. Don't peek too early!

back to top