Packaging Your Code: Methods#

A method is a way to name a section of code, to help organize code so that we don’t need to read a long file one line at a time, as that is difficult and requires a lot of concentration. Methods may also contain parameters so that the same code can work on different values, and this gives us the ability to reuse code, which makes coding faster. Methods may also return a value, which can then be used elsewhere in the program. There are several names that are often used instead of “method”: function, procedure, and subroutine. While there are technical differences, for example, that a function must return a value while a procedure cannot, we will not worry about them and may use the words interchangeably.

Syntax of Methods#

In order to name a section of code, there must be a container to put that code into. This container is formed by using a pattern of

<access modifiers> <return type> <method name> (<parameter list-data types and names>) {
\(\;\;\;\;\;\) <what the method does, i.e. the method body>
}

Example of a Method#

Here is an example of a method to find the average of three integers:

public static double getAverage(int num1, int num2, int num3){
   return (num1 + num2 + num3) / 3.0;
}

System.out.println(getAverage(1, 2, 3));
System.out.println(getAverage(31, 45, 2));
2.0
26.0

Let’s look at each part of this method definition:

  1. access modifiers. There are two: public and static. public means accessible everywhere and static means that no object is required to be made in order to use the method. For now, make all methods have public static access.

  2. return type. This is double and means that the method will send a floating point value back as its result.

  3. name. The method is called getAverage. Since methods usually do things, it is a good idea to use a verb as part of the method name.

  4. formal parameters. These are num1, num2 and num3. Each is of type int. Notice how the formal parameters are listed inside parentheses (), always as a data type followed by a parameter name. When the method is called, the actual parameters will match up to the formal ones and execution will use the actual parameters.

  5. squiggly brackets or braces. A method must have the code enclosed in {}.

  6. body. This is one statement for the example but can be longer. Since there is a return type, there must be a return statement. This method returns the result of calculating the sum of the three numbers and then divides that sum by 3.0. The three is made as a floating point number to force the result to have a decimal portion.

When this method is used, you will need to collect the return value somewhere, such as by assigning it to a variable or by printing the result. Here are two examples of how to collect the value:

1. double av;
2. av = getAverage(17, 10, 4); 

3. System.out.println("The average of 5, 2, 3 is: " + getAverage(5, 2, 3));

In line 2, the average value is placed into memory at the name av. This value is available for use later in the program. In line 3, the average value is concatenated onto the output string. Since the value has not been assigned to a variable, it is not available to use later in the program.

Semantics of Methods#

A method executes its code and returns a value (or sometimes nothing if the return type is void). The variables used in the method definition are placeholders and when the method is called then the actual parameters are bound to the placeholders. The rules for this binding vary depending on the data type of a variable:

  1. Primitive data is copied into the formal parameter. The value of the actual parameter is never changed by the method. Primitive parameters are never changed.

   public static void changeX(int x){ //Takes a primitive
      x = 19;
   }

   int w = 5;
   changeX(w);
   System.out.println(w);
5
  1. Reference data tends to be big (for example, think of an array to hold the phone numbers of everyone in Canada). For this reason, most reference data is not copied, but rather the method gets direct access[1]. This means that methods can change reference parameters.

   public static void changeX(int[] x){ //Now takes an array, which is reference type
      x[0] = 19;
   }

   int[] w = {5};
   changeX(w);
   System.out.println(w[0]);
19

A common problem for beginner programmers is to confuse the returning of values and printing of results. A print statement (for example, System.out.println) returns the value of null, but has an effect to display a string to the standard output window. Putting a print statement at the end of a method is not the same as returning a value. If a method returns a value, you won’t necessarily “see” it. You will need to pick up that value - by assigning it to a variable - and then print it if you want to see it.

Practice Questions#

  1. What is the return type of Java’s main method? What does this mean?

  2. Write the top line of a method that takes two integers and returns an integer that is the sum of the two parameters.

  3. Write the top line of a method that takes a string and an integer and returns a string that is the result of putting the integer onto both sides of the string.

  4. Write the complete method that takes two points, represented as four floating point numbers x1, y1, x2, y2 for (x1, y1) and (x2, y2). This method returns the slope of the secant line through those two points.

  5. Call your method from question 4) on the points (4, 5) and (3, 12) and assign the result to a new variable. List the formal parameters. List the actual parameters.

  6. Print the result you obtained in question 5.

  7. Write a method called printNumChars that takes an integer and a character and prints that number of characters to standard output. It does not print a newline.

  8. Write a method called stringNumChars that takes an integer and a character and returns a String with the correct number of the character. This method does not print anything.

To Solutions