Methods

Things To Do First

Things To Do Later

What Are Methods and Why Use Them?

What is a method? A method is basically a collection of statements that are placed together to perform some kind of task or operation.

Programmers write methods to modularize their programs. Program modules are smaller segments of program logic or code dedicated to a specific task. Modular programs are much easier to debug and maintain. Another reason programmers write methods is to make program code reusable. If you have a common programming task, you can put it in a method and then reuse it whenever you want without re-writing it every single time. Lastly, we write methods as a way of providing abstraction: details that aren't important. When you use Math.pow(), you know how to use it, you don't care how it actually works on the inside.

Modularization

Most programs you will write are going to be large and complex. Programmers develop these kinds of programs by breaking them up into smaller, more manageable tasks. Each task or module is coded into its own method. As a simple example, say a program calculates an employee's paycheck. You might have a sequence of methods such as:

  1. Get inputs (hours worked, rate of pay)
  2. Calculate gross pay
  3. Calculate tax deductions
  4. Calculate insurance deductions
  5. Calculate other deductions
  6. Calculate net pay
  7. Print paycheck
  8. Update payroll files

Re-usability

We also mentioned that we use methods to make code re-usable. Methods can help eliminate redundant code. Code that appears repeatedly are harder to maintain and debug, so programmers try to avoid repeating code. Methods are one way to do this. For example, imagine you are asking the user for the dimensions to calculate the volume of a three-dimensional rectangle:

import java.util.Scanner;

public class RectangleVolume {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        // get length
        System.out.println("Please enter the length.");
        double length = in.nextDouble();

        // get width
        System.out.println("Please enter the width.");
        double width = in.nextDouble();

        // get height
        System.out.println("Please enter the height.");
        double height = in.nextDouble();
        
        // calculate and display volume
        double volume = length * width * height;
        System.out.printf("The volume is %.2f.%n", volume);
    }
}

Here we are asking for three different values. We can make this code smaller and eliminate redundancy by using a method to get the user inputs.

Abstraction

The goal of abstraction is to hide the unnecessary details or internal workings of your code from the person using it (generally, another programmer). For example, if you create a method that calculates the average value in an array of integers, the person using your method doesn't need to know all the details of what's going on inside the method. They only need to know:

  1. What the method does (calculates the average of an integer array)
  2. What the method needs in order to do #1 (an array of integers)
  3. What the method returns, if anything, and what data type (a double value containing the average of all the array elements)

If you wrote this method and added a note such as "you must make sure your integer array is defined globally and called 'numbers'.." then you're not practicing abstraction: you're not hiding all the details inside the method. You're creating a method that is going to be difficult, if not impossible, to use.

Defining a Method

Figure 6.1 in chapter 6.2 shows you how a method is defined in your code. Turn to this diagram now and try the 9 questions, then check your answers.

A method definition starts with a heading, and the method's code goes between opening and closing braces. For example, you're already familiar with the main() method:

public static void main(String[] args)
{
	// code goes here
}

Not all method headings will be the same. For example, this method is called getUserInput(), and likely retrieves a value from the user:

public static String getUserInput(String msg)
{
	// method's code goes here
}

In general, a method's heading includes:

Introductory Examples

Let's start with a simple demonstration of how methods work. Enter the following program into your editor:

public class TestMethods {
    
    public static void main(String[] args)  {

        System.out.println("This is my main() method.");
        displayName();
        System.out.println("My main() method is finished.");
    }

    public static void displayName() {
        System.out.println("This is my displayName() method.");
        System.out.println("My name is [type your name here].");
        System.out.println("My displayName() method is finished.");
    }
}

The code that makes up a method goes in between the braces. In our program there are two methods: the main() method is defined from lines 03 to 08, and the displayName() is defined from lines 10 to 14.

On line 06 of the main() method you'll notice the method displayName() followed by a semi-colon. This is the method invocation or method call for the displayName() method. This is the statement that tells the computer to go and find the displayName() method and execute the statements inside it. When the computer gets to line 06, program execution will move to the displayName() method. All the statements inside the method will be executed, and then program control moves back to line 06 in the main() method. At this point, the program will continue with line 07, and then the program will terminate.

If you run this program, you'll get the following output:

This is my main() method.
This is my displayName() method.
My name is [type your name here].
My displayName() method is finished.
My main() method is finished.

Notice that the first and last line of output are the print statements in the main() method. The middle three lines are from the displayName() method.

Exercises

[solutions]

1. Write a program with a method called displayGreeting(). This method should display a greeting to the user (you decide what kind of greeting you'd like.. maybe something like "Hello, Welcome to my program that uses methods!" or "Yo, you got root.") Your main method should invoke the greeting method, and then display a closing message (such as "Cya l8r g8r!").

2. Modify the program in exercise 1 to put your closing message in a method called displayClosing(). Modify your main() method to invoke the greeting method, display some other text, and then invoke the closing method.

3. Manually trace the following program and determine the output, then run the program to see if you were correct.

public class TestMethods2 {
    public static void main(String[] args) 	{

        System.out.println("I have some methods:");
        displayOne();
        System.out.println("That's all!");
    }

    public static void displayOne() {
        System.out.println("This is method one.");
        displayTwo();
        System.out.println("Going back to main...");
    }

    public static void displayTwo() {
        System.out.println("This is method two.");
    }
}

4. Write a program that has a method called displayName(). This method should use a Scanner to ask the user for their name, then display that name on the screen in the form "Hello, [user name]!" (where [user name] is the name input by the user. The program's main() method should invoke the displayName() method, then display the message "Good bye!".

5. Write a program that displays "I love Java!" on the screen 10 times. Use a method called displayJava() to display the text 10 times.