AP® Computer Science A review sheet from Aim for Five (aimforfive.com/csa/units/3/3-5)
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
voidmethod- return type
returnstatement- 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.
- Example 1
Accessor and mutator together
Using the
Thermostatclass 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 solutionHide the solution
- Step 1: The constructor sets
targetto 68. - Step 2:
raise(5): is68 + 5 <= 80? 73 is at most 80, sotargetbecomes 73.getTarget()returns 73. - Step 3:
raise(10):73 + 10is 83, which is more than 80, so theelsesetstargetto 80.
Answer: Two lines:
73, then80. - Step 1: The constructor sets
- Example 2
Return from inside a loop
This method returns the index of the first space in
s. What dofirstSpace("ice cream cone")andfirstSpace("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 solutionHide the solution
- Step 1: For
"ice cream cone", the letters at indexes 0, 1 and 2 are i, c and e. Index 3 is a space. - Step 2: At
i= 3 theifis true, soreturn 3ends the loop and the method right away. The second space, at index 9, is never reached. - Step 3: For
"pie", no letter is a space, so the loop finishes and the method reachesreturn -1.
Answer:
firstSpace("ice cream cone")returns 3, andfirstSpace("pie")returns -1. - Step 1: For
Common mistakes
- Printing a value instead of returning it. If the method's header says
int, it mustreturnanint; printing doesn't count. - Putting
return -1;inside the loop'selse, so the method gives up after one check. - Writing a non-
voidmethod where some path has noreturn. Java rejects it with a compile error. - Calling a non-
voidmethod 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
Check yourself
3 questions on 3.5 Methods: How to Write Them. Pick an answer to see if you got it, and why.
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?
Which of the following methods compiles without error?
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