AP Computer Science A · Unit 3 lecture · Part 5 of 10 · 10 min

3.5 Methods: how to write themMethods: give back, or change

Mr. Thompkins
Every method you write answers one question first: does it give the caller something back, or does it change the object? Sometimes both. Get the header right and the body almost writes itself.

A method header has four parts: access (public or private), return type, name, and parameter list. public boolean use(int amount) is public, gives back a boolean, is named use and takes one int. A method that returns nothing has the return type void. A method that returns a value is a non-void method, and its return type says what kind of value.

?Wait, how do I use a void method versus a non-void one?
A void method call is a statement by itself: b.recharge(90);. A non-void call produces a value, so you use it inside something: store it, print it, or test it, as in if (b.use(25)). Writing int x = b.recharge(90); doesn't compile, because there's no value to store.

Two common kinds of methods have names. An accessor (often called a getter) returns information about the object and changes nothing. A mutator changes one or more instance variables. Mutators are often void, but they don't have to be: use below changes the charge and also returns whether it worked.

1public class Battery2{3    private int charge;45    public Battery(int start)6    {7        charge = start;8    }910    public int getCharge()111    {12        return charge;13    }1415    public void recharge(int minutes)216    {17        charge += minutes / 2;318        if (charge > 100)19        {20            charge = 100;21        }22    }2324    public boolean use(int amount)425    {26        if (amount > charge)27        {28            return false;429        }30        charge -= amount;31        return true;432    }3334    public boolean isLow()35    {36        return charge < 20;537    }38}
  1. line 10 Accessor: returns a value, changes nothing
  2. line 15 Mutator: void, changes charge
  3. line 17 int / int: 2 minutes per point, the decimal part is dropped
  4. line 24-31 Changes the state and also reports success
  5. line 36 Return a boolean expression directly
A Battery with an accessor, two mutators and a boolean method.
Statementcharge afterPrints
Battery b = new Battery(30);30
println(b.use(25) + " " + b.isLow());5true true
b.recharge(90);50
println(b.getCharge());5050
println(b.use(60) + " " + b.getCharge());50false 50
b.recharge(300);100
println(b.getCharge());100100
A trace of one Battery. Watch recharge(300): it adds 150, then the cap pulls charge back to 100.

A return statement does two things at once: it sends a value back to the caller and it ends the method right there. In use, if the amount is too big, return false; ends the method before the subtraction ever happens. That's why there's no else: the lines after it only run when the if was false. The value you return must match the return type, so a boolean method returns true, false or a boolean expression like charge < 20.

Java also insists that every possible path through a non-void method ends in a return. The compiler doesn't trust your logic; it checks the shape of the code.

1public String level()2{3    if (charge >= 50)4    {5        return "high";6    }7    else if (charge >= 20)18    {9        return "medium";10    }11}2
  1. line 7 If charge is 10, neither branch runs
  2. line 11 error: missing return statement
output › compile error: missing return statement
Two returns, but a path with none. The compiler stops you.
Pause and think
How would you fix level() so it compiles and returns "low" when the charge is under 20?
I thought about it. Show me
Turn the last branch into a plain else: else { return "low"; }, or put return "low"; after the whole if chain. Either way, every path now ends in a return, and the compiler can see that.

Parameters are copies

When you call a method, each argument's value is copied into the matching parameter. For primitive types like int, double and boolean, that means the method works on its own copy. Changing the parameter inside the method has no effect on the caller's variable. If you want the caller to get a new value, the method has to return it, and the caller has to store it.

1public static void addBonus(int score)12{3    score += 10;24    System.out.println("inside: " + score);5}6// in main7int points = 75;8addBonus(points);9System.out.println("outside: " + points);3
  1. line 1 score gets a copy of the value 75
  2. line 3 Changes the copy only
  3. line 9 points never changed
output › inside: 85 outside: 75
The method changes its own copy. The caller's variable is untouched.
in maininside addBonus75pointscopy the value85scorescore += 10 changes only the copypoints is still 75the copy disappears when the method ends
Two separate boxes: the caller's points and the method's score.
?Wait, what's a precondition again?
A precondition is something that must be true before a method is called, usually written in a comment, like "amount >= 0". The method doesn't have to check it, and on the FRQ you should assume it's true. A postcondition is what's guaranteed after the method finishes, like "charge is between 0 and 100".
Write the method
Add a method useUpTo(int amount) to Battery. It uses as much as it can, up to amount: if there's enough charge it uses all of amount, otherwise it uses whatever is left. It returns how much was actually used. Precondition: amount >= 0. For a battery at 30, useUpTo(12) returns 12 (18 left), then useUpTo(50) returns 18 (0 left).
1public int useUpTo(int amount)2{3    int used = amount;14    if (used > charge)15    {16        used = charge;17    }18    charge -= used;29    return used;210}11// in a client class12Battery c = new Battery(30);13System.out.println(c.useUpTo(12) + " " + c.getCharge());14System.out.println(c.useUpTo(50) + " " + c.getCharge());
  1. line 3-7 Use what was asked, but never more than is there
  2. line 8-9 Change the state, then report what happened
output › 12 18 18 0
  1. Header first: it answers "how much was used?", an int, so public int useUpTo(int amount).
  2. Start by assuming the full amount gets used: int used = amount;
    Why?
    A local variable is fine here. Nothing needs to remember it after the method ends.
  3. If that's more than what's there, use only what's there: if (used > charge) { used = charge; }
  4. Change the state: charge -= used; Then report: return used;
    Why?
    Update first, then return. A return before the update would end the method and skip it.
  5. Check it with the example: 12 is not more than 30, so used is 12 and charge goes to 18. Then 50 is more than 18, so used is 18 and charge goes to 0.

Answer: The method is public int useUpTo(int amount) { int used = amount; if (used > charge) { used = charge; } charge -= used; return used; }, and the test prints 12 18, then 18 0.

Stuck? Get a hint
  1. Which type does the method give back?
  2. Compute how much will be used before you change charge.
  3. The amount used is never more than charge. Subtract it, then return it.
Check yourself
What is printed by this code, using the Battery class above?
Battery b = new Battery(10);
b.recharge(25);
System.out.println(b.use(25) + " " + b.getCharge());
  1. Afalse 22
  2. Btrue 0
  3. Cfalse 35
  4. Dtrue -3
Show the answer

A. recharge(25) adds 25 / 2, which is 12 with integer division, so the charge is 22. use(25) asks for more than 22, so it returns false and changes nothing. The third choice is the top trap: it adds all 25 minutes instead of dividing by 2.

Exam tip from Mr. T

Read the verbs in the FRQ. "Returns" means a return statement. "Prints" means System.out.println. A method that should return a value but prints it instead loses the point, even when the printed value is right.

  • Header: access, return type, name, parameters. void returns nothing; a non-void method returns a value of its type.
  • Accessors report without changing. Mutators change instance variables, and may also return something.
  • return ends the method at once. Every path of a non-void method must end in a return.
  • Primitive arguments are copied. Changing a parameter never changes the caller's variable.
  • Assume preconditions are true. Methods don't need to check them.