πŸ““1.9: Method Signatures

Table of Contents


πŸ“– This page is a condensed version of CSAwesome Topic 1.9


Methods and Procedural Abstraction

Up until now, all of our code has been written as line-by-line statements in the main method, executed like step-by-step instructions, but complex programs are made up of many methods. We divide a program into methods to organize the code and avoid repetition.

Method
A named block of code that performs a task/process when it is called.

A block of code is any section enclosed in { }. These named blocks of code go by many names in different programming languages: functions, procedures, subroutines, etc. In Java they are called methods, as in a method of doing something.

In this unit, you will learn how to use methods written by other programmers. In latter units, you will learn how to write your own methods.

Procedural Abstraction
Allowing a programmer to use a method without knowing exactly how it works, i.e. "abstracting away" the details.

Procedural abstraction means we can use a method that someone else wrote without knowing exactly how it works. We just need to know the method’s name to call it and what it needs to do its job.

For example, we don’t need to know how a car exactly works in order to drive. πŸš— We know that if we hit the brakes, the car will stop; we can still use the brakes even if we don’t really know how they exactly work.

Method Calls

πŸ“£ A method call is when the code β€œcalls out” a method’s name to activate/run it. It always includes parentheses () and may include data inside.

methodName();

For example, when we write the statement System.out.println("Hello World");, we are calling the println() method to print out the text β€œHello World”.

Every method call is followed by parentheses. The parentheses () after method names are there in case you need to give the method some parameters/data to do its job, which we will see in the next lesson.

Example: Old MacDonald Song

This program in the shows how a song can be divided up into methods. Click on the next button below the code to β€œstep through” the code line-by-line, and watch the red arrow jump to the method that is being run.

πŸ‘‰ Execution of Java code always begins in the main method in the current class. Then, the flow of control skips from method to method as they are called. Notice that when a method ends, it returns to the line right after the method call.

Go into edit mode in the Visualizer and scroll down to the main() method. Add lines of code to the main method to print the second verse of the Old MacDonald Song:

  1. Call the method intro()
  2. Print out the line β€œAnd on that farm…” with a duck or another animal
  3. Call the method chorus()
  4. Print out the lines with the appropriate animal sounds
  5. Call the method intro() again

βœ‹ A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.

Method Signature/Header

When using methods in a library or API, we can look up the method signature/header) in its documentation.

A method header is the first line of a method that defines:

  • Method name
  • Return type (e.g., void means no return value)
  • Parameter list (variables and data types in parentheses; may be empty, but parentheses are required)

Example: PrintStream println Methods

From Oracle - Java Documentation:

  • println() – no parameters, just prints a new line
  • println(String x) – prints a String
  • println(int x) – prints an int

We can call these methods with the appropriate arguments to print out the value we want. The argument is the actual value that is passed to the method when it is called. Here are the method calls that correspond to the method signatures above:

  • System.out.println();
  • System.out.println("Hello World");
  • System.out.println(42);

image

Parameters vs. Arguments

We can make methods even more powerful and more abstract by giving them parameters for data that they need to do their job. This allows values, or arguments, to be passed and used by a method.

  • A parameter (β€œformal parameter”) is a placeholder variable declared in the method header.
  • An argument (β€œactual parameter”) is the value passed into the method when called.
    • The argument must be compatible with the parameter’s data type.

Example:

  • Signature: println(String x) β†’ parameter is String x
  • Call: println("Hello World"); β†’ argument is "Hello World"

Many people use the terms interchangeably, but technically the parameter is the placeholder and the argument is the value.

EXAMPLE: Old MacDonald Improved

Let’s take another look at the Old MacDonald Song and see if we can replace more repeated code with methods with parameters.

Notice that each verse of the song is similar, except it is about a different animal and the sound it makes. We can make a method called verse that takes the animal and its sound to print out any verse! The parameter variables animal and sound will hold different values when the method is called.

Step through this new version of the Old MacDonald program in the and watch how the argument are saved in the parameter variables with each call to the verse method.

Go into edit mode in the Visualizer and scroll down to the main() method. Add on to the song by calling methods as needed:

  1. Print another verse with the animal "goose" and the sound "honk" by calling the verse() method with the appropriate arguments.
  2. Then call intro() again.
  3. Repeat with another animal and sound of your choice.

Note that the main method can now just consist of calls to the intro() and verse() methods. Main methods often look like an outline for the program, calling methods to do the work.

When a method is called, the correct method definition (set of code instructions) is found by checking the method signature or header at the top of the method definition to match the method name, the number of arguments, the data types for the arguments and the return type.

// Method signature (parameters)
public static void verse(String animal, String sound) { }

// Method call (arguments)
verse("cow", "moo");

image

Here’s what that looks like with the two method calls above. The arguments like β€œcow” and β€œmoo” are saved into the parameter variables animal and sound with each method call.

Java uses call by value when it passes arguments to methods. This means that a copy of the value in the argument is saved in the parameter variable. Call by value initializes the parameters with copies of the arguments. If the parameter variable changes its value inside the method, the original value outside the method is not changed.

Overloading Methods

Methods are overloaded when they share the same name but have different parameter lists. The compiler determines which method to call based on the number and types of arguments passed to the method.

Example:

  • println() β†’ prints newline
  • println(String x) β†’ prints a string
  • println(int x) β†’ prints an integer

Summary

  • (AP 1.9.A.1) A method is a named block of code that only runs when it is called. A block of code is any section of code that is enclosed in braces.

  • (AP 1.9.A.1) Procedural abstraction allows a programmer to use a method by knowing what the method does even if they do not know how the method was written.

  • (AP 1.9.B.5) A method call interrupts the sequential execution of statements, causing the program to first execute the statements in the method before continuing. Once the last statement in the method has been executed or a return statement is executed, the flow of control is returned to the point immediately following where the method was called.

  • (AP 1.9.A.2) A parameter is a variable declared in the header of a method or constructor and can be used inside the body of the method. This allows values or arguments to be passed and used by a method or constructor.

  • (AP 1.9.A.2) A method signature for a method with parameters consists of the method name and the ordered list of parameter types. A method signature for a method without parameters consists of the method name and an empty parameter list.

  • (AP 1.9.B.3) An argument is a value that is passed into a method when the method is called. The arguments passed to a method must be compatible in number and order with the types identified in the parameter list of the method signature. When calling methods, arguments are passed using call by value.

  • (AP 1.9.B.3) Call by value initializes the parameters with copies of the arguments.

  • (AP 1.9.B.4) Methods are said to be overloaded when there are multiple methods with the same name but different signatures.


Acknowledgement

Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.