Lecture 21 (Tychonievich) - Methods

Lecture Date: Monday, March 2

Introduction

A method is a named collection of actions. Defining a method is like writing a how-to guide or recipe. Invoking, calling, or using a method is like following a how-to guide or cooking using a recipe.

We’ve been invoking methods since the first day of class. The syntax looks like ownerOfMethod.nameOfMethod(stuff, the, method, needs). Today we’ll start defining methods (other than main).

Classifying methods

Some methods belong to a particular object: for example, the Scanner method nextInt does a different thing depending on which Scanner’s nextInt method you use: each one reads from a different input source. Other methods belong to an entire class, not to any particular object: for example, the Math method sqrt computes the same square root independent of “which” Math you are using.

Methods that belong to a class are called static methods. You invoke them by NameOfClass.methodName(...) instead of nameOfObject.methodName(...). We’ll only look at static methods today.

Some methods create or return a value, and others do not. For example, Math.sqrt(9) returns the value 3.0; we would save or remember that value by writing, e.g., double x = Math.sqrt(9); or we would use it right away by writing, e.g., Math.sqrt(9) + 2. On the other hand, System.out.println(9) does not return a value. We call methods that do not return values void methods or say they have a void return type.

Some methods have side effects: they change something in some way. System.out.println() changes the text in the console (and is void); keyboard.nextLine() changes which line the keyboard Scanner is looking at (and also returns a String); list.add(13) changes what is stored in the list and the list’s size; etc. Many methods do not have side effects: Scanner’s hasNext, ArrayList’s size and get, Math’s sqrt, etc.

Defining a Method

A method definition has several parts, in order:

  1. A few keywords describing what kind of method it is. We’ll use public static for now.
  2. The type of value the method returns. If the method does not return a value, use void.
  3. The name of the method.
  4. Zero or more parameter declarations in parentheses. Parameter declarations look just like variable declarations: (int x, String y), etc. You need the parentheses even if there are no parameters.
  5. The method body: code inside curly braces.

Thus, for example, we might have

example method
1
2
3
4
public static int countChar(String text, char toCount) {
  String shorter = text.replace(""+toCount, "");
  return text.length() - shorter.length();
}

Methods, Memory, and Scope

When you invoke a method, the following happens in order:

  1. A new piece of memory (called a “stack frame” or “activiation record”) is created.
  2. The parameters of the method are created in that new memory.
  3. The arguments you pass in to the method invocation get copied into the new memory’s parameters in order.
  4. We note where we left off running the old method
  5. We stack the new memory on top of the old memory, covering up the old memory completely
  6. We start running the code in the new method’s body

When you return from a method, either with the return keyword or by reaching the end of the body, the new memory is removed (“popped”) from the stack, leaving us with the calling method’s memory.

We’ll walk through what that looks like for the following code in class:

In-class Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MethodCallExamples {
  public static int countChar(String text, char toCount) {
      String shorter = text.replace(""+toCount, "");
      return text.length() - shorter.length();
  }

  public static void main(String[] args) {
      String example = "kippers and marmalade";
      System.out.println(MethodCallExamples.countChar(example, "a"));
      String shorter = "wahoowa";
      int as = MethodCallExamples.countChar(shorter, "a");
      System.out.println("\"" + shorter + "\" has " + as + " 'a's");
  }
}

From lecture:

Question: public vs private?
Answer: public means other classes may use it

Question: What if you have a variable that is not in a method?
Answer: called fields, not variables; they need to be static to be used in static methods; they can break things in unexpected ways