A method header gives the method's access, the type of value it returns (or void for none), its name and its parameters. A method with a return type must reach a return with a value of that type on every path; a void method returns nothing and usually changes the object's instance variables. To trace calls on an object, update a table of its instance variables after every call.
Quick check
What does every method header have that a constructor header never has?Show answerHide answer
A return type, such as
int,booleanorvoid.In public Timer(int total), what is total?Show answerHide answer
A parameter: a variable that receives the value passed in when the constructor is called.
A header reads public int getScore(). What must the body do before it finishes?Show answerHide answer
Return an
intvalue with areturnstatement.
Know these already? Jump to the practice questions
What you'll be able to do
- Identify the parts of a method header.
- Choose the return type a method needs.
- Determine whether every path returns a value.
- Determine the state of an object after a sequence of calls.
- Explain how a method calls another method of its class.
Key terms
Return type
The type of value a method gives back, written before its name; void means nothing.
- In plain English
- What kind of answer the method hands back.
- Don't write
- "The return type is the type of the parameters."
Parameter
A variable in a method header that receives a value when the method runs.
- In plain English
- The empty slot the caller fills in.
- Don't write
- "A parameter is the value in the call."
Argument
The value placed in a method call, copied into the matching parameter by position.
- In plain English
- What you actually put in the slot.
- Don't write
- "Arguments are matched to parameters by name."
What does a method header tell you?
public int addPoints(int p, boolean bonus)
public means code outside the class can call it. int is the return type, so the call game.addPoints(5, true) is an int value you can store or print. addPoints is the name, and the parentheses hold the parameters, each with its type.
A call's arguments must match the parameters in number, type and order: the first argument is copied into the first parameter, whatever either is called.
A method that returns information without changing the object, such as getScore(), is an accessor. A method that changes instance variables, usually void, is a mutator.
Key idea
The header is a promise: the arguments must fit the parameter list, and the call evaluates to a value of the return type.
Check yourself
Show answerHide answer
double, the return type.
Does every path have to return a value?
Yes. If a method has a return type, every path through its body must end at a return with a value of that type. A return ends the method at once and hands the value back.
public String result(int score)
{
if (score >= 50)
{
return "pass";
}
}
This does not compile. When score is below 50 the body reaches its end without returning. Adding return "fail"; after the if closes that path.
The compiler checks the shape of the code, not the values of conditions. An if with no else can be skipped, so wrapping the last return in if (score < 50) still fails. End with a plain return or a final else.
Check yourself
Show answerHide answer
Yes: both the if branch and the else branch return an int.
What does a void method do?
A void method returns no value. Its job is usually to change the object's state, so you call it as a statement on its own, such as tank.fill(30);. Using it as a value, as in int x = tank.fill(30);, is a compile-time error.
A void method may use return; with no value to stop early. Writing return 5; in a void method is a compile-time error, and so is a bare return; in a method that has a return type.
Printing is not returning: System.out.println(total); shows the number, but the caller receives nothing it can store unless the method says return total;.
Check yourself
Show answerHide answer
A mutator: its void return type and its name show it changes the object's state instead of returning information.
How does a method use other methods of its class?
Inside a class, a method can call another method of the same class by its name alone: isFull() rather than tank.isFull(). The call runs on the same object, so it reads and changes the same instance variables.
public boolean isFull()
{
return level == capacity;
}
public void addOne()
{
if (!isFull())
{
level = level + 1;
}
}
When you trace, step into the called method, work out its return value, then carry it back to the line that called it.
Check yourself
Show answerHide answer
The same object addOne was called on.
Worked example 1: Trace a sequence of calls
Question: What is printed when this code runs?
public class Tank
{
private int level;
private int capacity;
public Tank(int cap)
{
capacity = cap;
level = 0;
}
public void fill(int amount)
{
level = level + amount;
if (level > capacity)
{
level = capacity;
}
}
public void use(int amount)
{
if (amount <= level)
{
level = level - amount;
}
}
public boolean isFull()
{
return level == capacity;
}
public int getLevel()
{
return level;
}
}
Tank t = new Tank(50);
t.fill(30);
t.use(45);
t.fill(25);
System.out.println(t.getLevel() + " " + t.isFull());
t.use(20);
System.out.println(t.getLevel());
What tells you the method
Several calls change one object, so keep a trace table of its instance variables.
Step 1: Trace each call.
Call levelcapacityNote new Tank(50)0 50 fill(30)30 50 30 ≤ 50 use(45)30 50 45 > 30, no change fill(25)50 50 55 capped at 50 use(20)30 50 20 ≤ 50 WhyEach
voidcall changeslevel, and the next call starts from that new value.Step 2: Evaluate the prints.
The first
printlnruns afterfill(25):getLevel()is 50 andisFull()istrue. The second runs afteruse(20)and prints 30.WhyA print shows the state at the moment it runs.
Check it
use(45) is the boundary case: 45 is more than the 30 in the tank, so the if is false and nothing is taken.
Answer
50 true then 30 on the next line.
Worked example 2: Design a method that calls another
Question: Add two methods to Tank: spaceLeft(), returning how much more the tank can hold, and fillIfRoom(int amount), which fills only if amount fits and reports whether it did. What is printed?
Tank t = new Tank(50);
t.fill(30);
boolean a = t.fillIfRoom(15);
boolean b = t.fillIfRoom(10);
System.out.println(a + " " + b + " " + t.getLevel());
What tells you the method
A design task: choose headers, reuse methods, then trace.
Step 1: Choose the headers.
spaceLefttakes nothing and gives a number:public int spaceLeft().fillIfRoomtakes an amount and answers yes or no:public boolean fillIfRoom(int amount).WhyThe return type follows from what the caller needs back.
Step 2: Write the bodies, reusing
fill.public int spaceLeft() { return capacity - level; } public boolean fillIfRoom(int amount) { if (amount <= spaceLeft()) { fill(amount); return true; } return false; }WhyBoth paths of
fillIfRoomend in areturn, so it compiles.Step 3: Trace.
After
fill(30),spaceLeft()is 20. 15 ≤ 20, solevelbecomes 45 andaistrue. NowspaceLeft()is 5; 10 > 5, sobisfalseandlevelstays 45.WhyThe second call sees the state the first call left.
Check it
At the boundary, fillIfRoom(5) at level 45 gives 5 ≤ 5, so it returns true and the tank holds 50.
Answer
true false 45
Worked example 3: Close every path
Question: category should return "child" under 13, "teen" for 13 to 19 and "adult" from 20, but it does not compile. Which change fixes it?
1: public String category(int age)
2: {
3: if (age < 13)
4: {
5: return "child";
6: }
7: else if (age < 20)
8: {
9: return "teen";
10: }
11: }
- A) Change line 1 to
public void category(int age) - B) Insert
return "adult";between lines 10 and 11 - C) Change line 7 to
if (age < 20) - D) Insert
else if (age >= 20) { return "adult"; }between lines 10 and 11
What tells you the method
A non-void method fails to compile, so look for a path with no return.
Step 1: Find the open path.
For age 20 or more, both conditions are false and the body ends with no
return.WhyThe
else ifhas no finalelse, so it can be skipped.Step 2: Test each option.
B returns "adult" on that path. A makes
return "child";an error in avoidmethod. C leaves the open path. D still ends in anifwith noelse; the compiler does not reason that the conditions cover every age.WhyOnly an unconditional
returncloses the path.
Check it
With B, ages 12, 13, 19 and 20 give "child", "teen", "teen" and "adult".
Answer
B
Your turn
Question: What is printed when this code runs?
public class Player
{
private int points;
private int lives;
public Player()
{
points = 0;
lives = 3;
}
public void score(int p)
{
points = points + p;
if (points >= 100)
{
lives++;
points = points - 100;
}
}
public void hit()
{
lives--;
}
public String status()
{
return points + "/" + lives;
}
}
Player p = new Player();
p.score(70);
p.hit();
p.score(45);
System.out.println(p.status());
Step 1: Trace the first two calls.
score(70)makespoints70, below 100, solivesstays 3.hit()makeslives2.Step 2: Your go: trace
score(45)and build the printed string.
Show the full solutionHide the solution
Step 2. points becomes 115, which is at least 100, so lives goes up to 3 and points drops to 15. status() returns "15/3".
Answer: 15/3
Traps
Trap
Arguments are matched to parameters by their names.
It seems right because the names often match. But Java copies arguments into parameters by position: the first argument goes to the first parameter, whatever either is called.
For move(int dx, int dy), with int dx = 5; and int dy = 2;, what does the parameter dx hold during move(dy, dx)?
2, the value of the first argument.
Trap
Code after a return inside an if still runs on that call.
It seems right because the method has more lines. But return ends the method at once, so the rest is skipped on that call.
What does f(5) return, where f is int f(int x) { if (x > 0) { return 1; } x = x + 10; return x; }?
- The line
x = x + 10;never runs on that call.
What's examined
On the AP® Computer Science A exam (Unit 3: Class Creation), multiple-choice questions ask you to trace calls on an object, pick a header or find the code that completes a method. In free response you write methods, so check the header, a return on every path and the changes to state.
Practice questions
- Recall Which header fits a method that takes a
Stringand anintand gives backtrueorfalse?
- A)
public void check(String s, int n) - B)
public check(String s, int n) - C)
public boolean check(s, n) - D)
public boolean check(String s, int n)
Show answer
Answer: D. The return type boolean comes before the name, and each parameter has a type.
Why the others are wrong:
- A has return type
void, so it cannot give backtrueorfalse. - B has no return type, which only a constructor may omit.
- C leaves out the parameter types.
- Recall Name the return type of a method that returns no value.
Show answer
Answer: void
Marking points:
- A
voidmethod can usereturn;but neverreturnwith a value.
- Apply What is printed?
public class Parcel
{
public String sizeOf(int cm)
{
if (cm > 150)
{
return "large";
}
if (cm > 90)
{
return "medium";
}
return "small";
}
}
Parcel p = new Parcel();
System.out.println(p.sizeOf(150) + " " + p.sizeOf(151));
Show answer
Answer: medium large
Marking points:
- 150 is not greater than 150, so the first
returnis skipped; 150 > 90 returns "medium". - 151 > 150 returns "large" at once.
- Apply What is printed?
public class Wallet
{
private int cash;
public Wallet(int start)
{
cash = start;
}
public boolean spend(int cost)
{
if (cost > cash)
{
return false;
}
cash = cash - cost;
return true;
}
public void earn(int hours)
{
cash = cash + hours * 12;
}
public int getCash()
{
return cash;
}
}
Wallet w = new Wallet(20);
System.out.println(w.spend(25));
w.earn(3);
System.out.println(w.spend(25));
System.out.println(w.getCash());
Show answer
Answer: false then true then 31, each on its own line.
Marking points:
- 25 > 20, so the first
spendreturnsfalseandcashstays 20. earn(3)adds 36, making 56;spend(25)returnstrueand leaves 31.
- Exam-style The method should return the mean of the
intinstance variabless1,s2ands3as adouble. With 7, 8 and 8 it returns 7.0, not about 7.67. Line 3 stays as it is. Give the number of the line that causes this.
1: public double average()
2: {
3: int total = s1 + s2 + s3;
4: return total / 3;
5: }
Show answer
Answer: Line 4.
Marking points:
total / 3isintdivision: 23 / 3 is 7, which only then becomes 7.0.- The fix is
return total / 3.0;, which returns 7.666….
- Exam-style A class has
private int charge;and a methodpublic boolean isLow()that returnscharge < 20. Which body forpublic String warning()returns "LOW" when the charge is low and "OK" otherwise?
- A)
if (isLow) { return "LOW"; } return "OK"; - B)
if (isLow()) { return "LOW"; } - C)
if (isLow()) { return "LOW"; } return "OK"; - D)
if (charge.isLow()) { return "LOW"; } return "OK";
Show answer
Answer: C. It calls isLow() on the same object and returns on both paths.
Why the others are wrong:
- A leaves off the parentheses, so
isLowis read as a variable that does not exist. - B has no
returnwhen the charge is not low, so it does not compile. - D calls a method on
charge, anint, which has no methods.
- Exam-style What is printed?
public class Step
{
private int x;
public Step(int start)
{
x = start;
}
public int twice()
{
return x * 2;
}
public void advance()
{
x = twice() - 1;
}
public int getX()
{
return x;
}
}
Step s = new Step(3);
s.advance();
s.advance();
System.out.println(s.getX() + s.twice());
Show answer
Answer: 27
Marking points:
- The first
advancesetsxto 3 × 2 − 1 = 5; the second sets it to 5 × 2 − 1 = 9. getX() + twice()adds twoints, 9 + 18, so it prints 27, not "918".
- Apply A class has the method
public double cost(int qty, double each), andobjrefers to an object of that class. Which statement compiles?
- A)
double c = obj.cost(3, 2.5); - B)
int c = obj.cost(3, 2.5); - C)
double c = obj.cost(2.5, 3); - D)
double c = obj.cost(int 3, double 2.5);
Show answer
Answer: A. The arguments match the parameters in type and order, and the result is stored as a double.
Why the others are wrong:
- B stores a
doublereturn value in anint, which Java does not allow without a cast. - C swaps the arguments, so 2.5 would go into the
intparameterqty. - D writes types inside the call; types belong only in the header.
Key points
Recall, then reveal
Say the main points from memory first, then check them.
Show key pointsHide key points
- A header gives access, return type, name and typed parameters.
- Arguments fill parameters by position, matching type and order.
- A non-
voidmethod needs areturnon every path;returnends the method at once. - A
voidmethod changes state and cannot be used as a value. - Calling
isFull()inside the class runs it on the same object.