Skip to main content

Unit 3 · Topic 3.5

3.5 Methods: How to Write Them

Methods are an object's behaviors. This topic covers writing void and non-void methods, how return works, accessor and mutator methods, and what happens to primitive values passed as parameters.

Key terms

  • void method
  • return type
  • return statement
  • accessor method
  • mutator method

Reading a method header

A method header has four parts: an access keyword (public or private), a return type (or void), the method's name, and a parameter list in parentheses, where each parameter has a type and a name. In public void raise(int degrees), the method is public, returns nothing, is named raise and takes one int. On the exam, copy headers exactly as the question gives them.

void and non-void methods

A void method does a job and returns nothing. Its header has the keyword void before the method name, like public void raise(int degrees). You call it as a statement on its own.

A non-void method returns exactly one value. Its header has the return type in place of void, like public int getTarget(). Every path through the method must reach a return with a value of that type. The caller gets a copy of the value, which is called return by value, and usually stores it, prints it or uses it in an expression.

How return works

A return statement sends control straight back to where the method was called. Nothing after it in the method runs. If a return is inside a loop or an if, it ends the loop and the whole method on the spot.

Code placed directly after a return in the same block can never run, and Java treats that as a compile error. A void method can use a plain return; to leave early.

Accessors and mutators

An accessor method (a getter) lets other classes see the value of an instance variable or class variable. It's non-void and hands back a copy of the value, like getTarget() returning an int.

A mutator method (a setter or modifier) changes instance or class variables. It's usually void. A good mutator can enforce rules, like this thermostat, which never goes above 80:

public class Thermostat { private int target; public Thermostat(int start) { target = start; } public int getTarget() { return target; } public void raise(int degrees) { if (target + degrees <= 80) { target += degrees; } else { target = 80; } } }

Parameters

Parameters let a method receive values to work with. When the argument is a primitive, the parameter gets a copy of the value. Changing the parameter inside the method has no effect on the caller's variable. (Objects are different; see 3.6.)

Worked examples

Try each one yourself first, then open the solution.

  1. Example 1

    Accessor and mutator together

    Using the Thermostat class above, what does this code print?Thermostat t = new Thermostat(68); t.raise(5); System.out.println(t.getTarget()); t.raise(10); System.out.println(t.getTarget());

    Show the solution
    1. Step 1: The constructor sets target to 68.
    2. Step 2: raise(5): is 68 + 5 <= 80? 73 is at most 80, so target becomes 73. getTarget() returns 73.
    3. Step 3: raise(10): 73 + 10 is 83, which is more than 80, so the else sets target to 80.

    Answer: Two lines: 73, then 80.

  2. Example 2

    Return from inside a loop

    This method returns the index of the first space in s. What do firstSpace("ice cream cone") and firstSpace("pie") return?public static int firstSpace(String s) { for (int i = 0; i < s.length(); i++) { if (s.substring(i, i + 1).equals(" ")) { return i; } } return -1; }

    Show the solution
    1. Step 1: For "ice cream cone", the letters at indexes 0, 1 and 2 are i, c and e. Index 3 is a space.
    2. Step 2: At i = 3 the if is true, so return 3 ends the loop and the method right away. The second space, at index 9, is never reached.
    3. Step 3: For "pie", no letter is a space, so the loop finishes and the method reaches return -1.

    Answer: firstSpace("ice cream cone") returns 3, and firstSpace("pie") returns -1.

Common mistakes

  • Printing a value instead of returning it. If the method's header says int, it must return an int; printing doesn't count.
  • Putting return -1; inside the loop's else, so the method gives up after one check.
  • Writing a non-void method where some path has no return. Java rejects it with a compile error.
  • Calling a non-void method and ignoring its result when you needed it.

On the exam

  • Free-response methods are scored on whether they return the right value in every case. Before you finish, check what happens on the very first pass, the very last pass, and when nothing matches.

Connected topics

Videos

  • AP Computer Science A - Topic 3.5 - Part 1: Writing Mutator Methods

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • Methods: How to Write Them

    CodeHSWatch on YouTube (opens in a new tab)

  • AP CSA Class Creation – Accessor and Mutator Methods

    Goldie's Math EmporiumWatch on YouTube (opens in a new tab)

  • AP Computer Science A - Topic 3.5 - Part 2: Writing Accessor Methods

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

  • Getters & Setters (Java Tutorial)

    Bill BarnumWatch on YouTube (opens in a new tab)

  • AP Computer Science A - Topic 3.5 - Part 3: Writing methods with Pre- and Post- Conditions

    Tim Gallagher Computer ScienceWatch on YouTube (opens in a new tab)

Check yourself

3 questions on 3.5 Methods: How to Write Them. Pick an answer to see if you got it, and why.

Question 1 of 3

Consider the following method.public static int smallestFactor(int n) { for (int k = 2; k < n; k++) { if (n % k == 0) { return k; } } return n; }The following code segment appears in another method of the same class.System.out.println(smallestFactor(91) + " " + smallestFactor(13));What is printed as a result of executing the code segment?

Question 2 of 3

Which of the following methods compiles without error?

Question 3 of 3

Consider the following method.public static int process(int n) { if (n > 10) { return n - 10; } n = n * 2; return n; }What value is returned by process(15) + process(4)?

0 of 3 answered