Skip to content

Course navigation

For teachersTopic 3.5 · Lesson kit

Methods: How to Write Them

  • 3 class periods
  • 45 minutes each
  • Objective 3.5.A
  • 6 downloads with keys

Downloads

  • Slides

    Speaker notes on every slide

  • Lesson plan

    3 periods of 45 minutes

  • Worksheet

    Puzzles, about 30 minutes

  • Worksheet key

    Answer key

  • Exit ticket

    End of the last period

  • Exit ticket key

    Answer key

Download all AP CSA teacher filesEvery topic's slides, lesson plan, worksheet, and exit ticket, with keys (.zip)

At a glance

Pacing
3 class periods of 45 minutes
Learning objectives
3.5.A
Essential knowledge
3.5.A.13.5.A.23.5.A.33.5.A.43.5.A.53.5.A.63.5.A.73.5.A.8
Materials
Projector and the Give It Back slide deckWhiteboard and markersMini whiteboards or scrap paper (traces)IDE on every computerPrinted Give It Back puzzle worksheet (answer key for you) and exit ticket

45 minutes a day

Agenda

Day 145 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  1. 0:00–0:055 minWarm-upask it, or tell it? (slide 2)
  2. 0:05–0:1510 minDirect instructionvoid and non-void headers (slides 3–5)
  3. 0:15–0:2510 minDirect instructiona mutator changes the object (slide 6)
  4. 0:25–0:305 minDirect instructionchanging the parameter changes nothing (slide 7)
  5. 0:30–0:4010 minGuided practiceturn it up (slide 8) and worksheet question 7
  6. 0:40–0:455 minClosuremutator in one sentence

Day 245 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Closure
  1. 0:00–0:055 minWarm-upwhat comes back?
  2. 0:05–0:1510 minDirect instructionthe call becomes the returned value (slides 9–10)
  3. 0:15–0:238 minDirect instructionan accessor hands back a copy (slide 11)
  4. 0:23–0:307 minDirect instructionthe call must match the return type (slide 12)
  5. 0:30–0:4010 minGuided practicepick the header (slide 13) and worksheet question 2
  6. 0:40–0:455 minClosureworksheet question 1 (face-off)

Day 345 minutes

  • Warm-up
  • Direct instruction
  • Guided practice
  • Activity
  1. 0:00–0:055 minWarm-upwhere does it stop?
  2. 0:05–0:138 minDirect instructionthe first return that runs wins (slides 14–15)
  3. 0:13–0:207 minDirect instructiona return inside a loop (slide 16)
  4. 0:20–0:255 minDirect instructionevery path needs a return, and nothing after it (slide 17)
  5. 0:25–0:338 minDirect instructionparameters get copies (slides 18–19)
  6. 0:33–0:407 minGuided practicetwo copies in one program (slide 20) and worksheet question 3
  7. 0:40–0:455 minActivityDay 3 closure and exit ticket (slides 21–22)

Overview

Students write their own methods for the first time (3.5.A). In Topics 1.9 to 1.15 they called methods someone else wrote; in Topic 3.3 they saw short methods with no parameters; in Topic 3.4 they wrote constructors. Day 1 is the void method and the mutator (3.5.A.1, 3.5.A.6, 3.5.A.7): a method that hands nothing back, whose call is a statement on its own, and which uses its parameters to change instance variables. Day 2 is the non-void method and the accessor (3.5.A.2, 3.5.A.3, 3.5.A.5): a method that returns one value compatible with its return type, so the call becomes that value, and an accessor hands back a copy of an instance variable’s value. Day 3 is the return keyword as “leave now” (3.5.A.4), including inside an if and a loop, and call by value for primitive parameters (3.5.A.8).

One question runs through all three days, from the slide 2 warm-up to the slide 22 closure: does this method give something back, or does it change the object?

Stay inside the topic boundary. Every parameter and return value is a primitive (int, double, boolean). Passing and returning object references is Topic 3.6, writing static methods and class variables is Topic 3.7, local-variable scope as a named idea is Topic 3.8, and this is Topic 3.9. If a student asks why a parameter can’t share an instance variable’s name, say that Topic 3.9 answers it and keep the names different today.

Teacher note

The slides are the Give It Back deck (22 slides, with speaker notes); slide numbers below refer to it. Day 1 uses slides 1–8, Day 2 uses slides 9–13, and Day 3 uses slides 14–22. The Give It Back puzzle worksheet (9 questions, about 30 minutes) is split across the three days: question 7 in class on Day 1, questions 2 and 1 in class on Day 2 and question 5 as Day 2 homework, question 3 in class on Day 3, and questions 4, 6, 8, and 9 as Day 3 homework. The Think First box at the top of Part A asks for a guess that question 8 settles; have students write the guess on Day 1.

All demonstration files are in the topic’s examples/ folder. Open them in the IDE before class so each demo is one click.

  • Day 1 demonstrations: FirstVoidMethod, MissingReturnType (compile error), AddSteps, ResetSteps, TwoTrackers, MutatorWrong.
  • Day 2 demonstrations: StepsToGoal, GoalChecks, Accessors, AccessorCopy, AccessorAssign (compile error), VoidAsValue (compile error), LossyReturn (compile error).
  • Day 3 demonstrations: BadgeLevel, EarlyVoidReturn, DaysToGoal, Unreachable (compile error), MissingReturn (compile error), CopyTrace, DepositSameName, ParameterAsResult.
  • Printed only (exit ticket): ExitTicketTrace and ExitPlant.

Day 1 · Warm-up: Ask it, or tell it?

Show slide 2. Pairs get two minutes to sort four requests you could make of a water bottle. Requests 1 (“How many ounces are left?”) and 3 (“Are you empty?”) give an answer back and leave the bottle alone; requests 2 (“Drink 10 ounces”) and 4 (“Refill to the top”) change the bottle and give nothing back. Write the two columns on the board and keep them up all week: that split is the whole topic. Before moving on, hand out the worksheet and have students write their Think First guess in the margin: does changing an int parameter to 0 change the caller’s variable?

Day 1 · Direct instruction: Void and non-void headers

  1. Goals (slide 3). Read the six goals: 1–2 are today’s, 3–4 are Day 2’s, and 5–6 are Day 3’s. Slide 4 opens Part 1.
  2. Two kinds of header (3.5.A.1, 3.5.A.2, slide 5). A void method does not return a value; its header has void before the name, as in public void drink(int amount). A non-void method returns a single value; its header puts that value’s type where void would go, as in public int getOunces(). Point at the two calls on the slide: b.drink(10); is a statement on its own line, and b.getOunces() is a value you print or store. Connect the two columns to the warm-up’s two columns.
  3. A void method in a class. Run FirstVoidMethod: printSummary is written inside StepTracker, uses the private instance variable steps, and is called with a dot from main. The output shows the call running in the middle of main and control coming back to the next line. Run TwoTrackers to show that the same method prints each object’s own steps.
  4. Every header needs a return type. Show MissingReturnType and its error, invalid method declaration; return type required. “Nothing comes back” is said with the word void; only a constructor has no return type, and its name matches the class.

Misconception: A void method doesn't need a return type

Students who hear “void returns nothing” leave the return type out entirely. Java rejects the header with return type required. Have students read every header in the order the slide 5 box gives: return type, then name, then parameters. Only a constructor skips the return type, and that’s how Java tells it apart from a method.

Day 1 · Direct instruction: A mutator changes the object

  1. The worked example (3.5.A.6, 3.5.A.7, slide 6). Read WaterBottle with the class. drink(int amount) receives a value through its parameter and uses it to do its job (3.5.A.7): it subtracts amount from ounces, then the if stops ounces at 0. A method that changes an object’s instance variables is a mutator, and a mutator is often void.
  2. Trace main on the board before you reveal the output. ounces starts at 24; drink(10) makes 14; drink(30) makes -16, and the if sets it to 0. Output: 14, then 0. Ask: “Which line changed ounces?” The answer is the assignment with ounces on the left.
  3. Demo. Run AddSteps (two calls to addSteps build on each other: 6700, then 7500), then ResetSteps, a mutator with no parameter that sets steps to 0 (prints 300). A mutator can take parameters or not; what makes it a mutator is that it changes instance variables.

Day 1 · Direct instruction: Changing the parameter changes nothing

Show slide 7. Both versions of addTime compute minutes + coins * 15, but the bug stores the answer in the parameter coins, which disappears when the method ends. After addTime(2) the bug leaves minutes at 0 and the fix makes it 30. Then run MutatorWrong: it compiles and prints Steps so far: 4200, as if the walk never happened. Ask students to point at the variable on the left of = in each version; that’s the one that changes.

Misconception: Storing the result in the parameter

Students think of “the variable in the method” as the one that matters, so they assign to the parameter. The code compiles and computes the right number, and the object never changes. Teach the check: in a mutator, the left side of the assignment must be an instance variable. Worksheet question 7 is this exact bug.

Day 1 · Guided practice: Turn it up

  1. Slide 8 (pause and try). Students trace Dimmer on whiteboards. Answer: 10, then 6. Dimmer has no constructor, so level starts at its default, 0 (Topic 3.4). up(3) makes 3; up(9) makes 12 and the if caps it at 10; up(-4) makes 6. Each call changes the same object’s level.
  2. Worksheet question 7 (one-token fix) in pairs. Line 7 should read points = points + bonus;: change the first bonus to points. The original stores 15 in the parameter, which disappears when addBonus ends, so getPoints still returns 10. Ask pairs to say why in one sentence, not only which token.

Teacher note

On slide 8, watch for students who write 12 for the first line: they ran the addition but skipped the if. Ask them to read the method body one line at a time, in order, for each call.

Day 1 · Closure: Closure

Students finish this sentence in their notes: “A mutator __ the object and is usually __.” (changes; void). Collect a few aloud and keep the Day 2 half of the slide 22 starter for tomorrow.

Day 2 · Warm-up: What comes back?

Show StepsToGoal without running it. Students write both lines of output on whiteboards. Answer: Steps left: 5800 and Laps left: 11 (5800 / 500 with int division). Then ask: “In the second line, what did tracker.stepsToGoal() turn into?” The value 5800. That’s today’s idea.

Day 2 · Direct instruction: The call becomes the returned value

  1. Return by value (3.5.A.3, slides 9–10). In a non-void method, return evaluates its expression and sends back that value; this is return by value. On slide 10, r.area() evaluates width * height, 24, and the call is replaced by 24, so a + 1 prints 25. ratio() returns (double) width / height, 1.5; the cast happens before the division (Topic 1.5).
  2. Compatible with the return type. The returned value must fit the header’s return type: int for area, double for ratio. Run GoalChecks: milesWalked returns a double (2.1), and reachedGoal returns a boolean that an if uses directly (Topic 2.3).
  3. What the caller does with it. A returned value can be stored, printed, or used in a bigger expression. If the caller ignores it, the value is simply lost.

Misconception: The return type doesn't have to match

Students pick the return type first and then write any expression. Show LossyReturn: steps / 2000.0 is a double, the header says int, and Java reports possible lossy conversion from double to int. Java won’t silently drop part of a value. Fix it by making the return type double. An int value returned from a double method is fine, as worksheet question 6, method 3, shows.

Day 2 · Direct instruction: An accessor hands back a copy

  1. Accessor (3.5.A.5, slide 11). An accessor is a non-void method that lets code outside the class get a copy of an instance variable’s value. The instance variable stays private; the accessor is the window into it. Run Accessors: getSteps and getGoal read the values, and addSteps is the mutator between them.
  2. A copy, not the variable. Trace slide 11: left gets a copy of 24, left = 0 changes only the copy, and the output is 0 24. Run AccessorCopy (prints 0, then 4200) to see it again.
  3. A call is a value, not a variable. Show the bottom of slide 11 and AccessorAssign: b.getOunces() = 0; gives error: unexpected type. You can’t assign to a value. To change the object, call a mutator.

Misconception: Changing a value through an accessor

Students expect tracker.getSteps() = 0; or int s = tracker.getSteps(); s = 0; to change the object. The first doesn’t compile, and the second changes only the caller’s copy. Ask: “Which method in this class changes steps?” If there isn’t one, nothing outside the class can change it, and that’s the point of private instance variables.

Day 2 · Direct instruction: The call must match the return type

Show slide 12 and run both errors. VoidAsValue stores a void call (int shown = tracker.printSummary();): void cannot be converted to int; the slide’s System.out.println(b.drink(5)); gives 'void' type not allowed here. There’s nothing to print or store, so the fix is b.drink(5); on its own line. The right half is slide 10’s rule broken: ounces / 2.0 is a double in an int method. Give students the slide’s two questions to ask of every method: does it return anything, and if so, does the returned value fit the return type?

Misconception: Using a void call as a value

Students print or store every call because they’ve used Math and String methods that way. A void call has no value, so System.out.println(b.drink(5)); doesn’t compile. Have students look up the return type in the header before they decide whether a call goes on its own line or inside an expression.

Day 2 · Guided practice: Pick the header

  1. Slide 13 (pause and try). Students hold up A, B, C, or D. Answer: C, public boolean hasWater(). The body returns ounces > 0, a boolean. A: a void method can’t return a value. B: a boolean can’t be converted to int. D: every method needs a return type.
  2. Worksheet question 2 (pencil check) in pairs. count goes 8, 8, 16, 16, 7, 7, and the calls return nothing, 8, nothing, true, nothing, false. Only the add rows change count. Ask pairs to label each method in the Counter class: mutator, accessor, or neither (isEven returns a value computed from count and changes nothing).

Day 2 · Closure: Closure

Students fill in worksheet question 1 (face-off) alone, then compare with a partner. Key words: non-void, copy, void, instance variables, the instance variable stays the same, argument. Question 5 (snippet pool) is homework; the holes are amount, double, and temp < 18.0.

Day 3 · Warm-up: Where does it stop?

Show EarlyVoidReturn without running it. Students write the output. Answer: Ignored: -300, Added: 600, 4800. The return; on the first call ends the method before steps changes. Point out that a void method can say return; with no value; it can’t return a value, because its header promised nothing comes back. (The Fair Question box on the worksheet before question 5 says the same.)

Day 3 · Direct instruction: The first return that runs wins

  1. Return ends the method (3.5.A.4, slides 14–15). The return keyword sends control back to the point where the method was called. A return inside an if ends the whole method, not just the if.
  2. Trace fine() for the three books on slide 15. -2 hits the first return 0. 3 skips both ifs and returns 3 * 25, 75. 30 hits return 500, and daysLate * 25 never runs. Output: 0, 75, 500. Then run BadgeLevel (2, 3, 1): the order of the ifs matters, because the first return that runs wins.

Day 3 · Direct instruction: A return inside a loop

Slide 16. A return inside a loop stops the loop and the method. Fill in the trace table with the class: with weekly 15, total reaches 105 in week 7, so weeksUntil(100) returns 7 and the loop never sees week 8. For a goal of 1000, the loop runs all 52 weeks without a match, ends normally, and return -1; runs. Run DaysToGoal (3, then -1) for the same pattern. Ask: “Why does the method need the return -1; after the loop?” Because a non-void method must return a value even when the loop never finds a match.

Day 3 · Direct instruction: Every path needs a return, and nothing after it

Show slide 17 and run Unreachable and MissingReturn. Code right after a return in the same block can never run, and Java reports unreachable statement; move the print above the return. A non-void method must return a value on every path; isRich has none when the if is false, and Java reports missing return statement; add return false; after the if.

Misconception: return means remember the answer

Students write code after a return, expecting it to run, because they think of return as storing the answer and carrying on. return means leave now. Have students say “leave now” out loud when they reach a return in a trace.

Misconception: An if with a return covers every case

Students write one return inside an if and stop, so the method has no value when the condition is false. Java rejects it with missing return statement. Ask, for each method: “If every if is false, which return runs?” There must be one.

Day 3 · Direct instruction: Parameters get copies

  1. Call by value (3.5.A.8, slides 18–19). When the argument is a primitive, the parameter starts as a copy of the argument’s value. Trace slide 19: score is 250, points starts as a copy of 250, points = points / 10 makes the copy 25, and 25 tickets are added. score is still 250. Output: 250 25. Two separate variables; only the copy changes.
  2. Demo. Run CopyTrace: collect doubles its parameter twice over two calls, gift stays 25, and raised is 200. Then run DepositSameName: the parameter has the same name as main’s variable, cash = 0 inside the method, and main’s cash is still 20.0. Same name, different variable.
  3. Sending an answer back. Run ParameterAsResult: a void method stores its answer in a parameter, and main prints 0. The way a method sends a primitive answer back is a return value: int left = tracker.stepsToGoal();. Now settle the Day 1 Think First guess: no, the caller’s variable never changes.

Misconception: Changing the parameter changes the argument

Students picture the parameter as the caller’s variable under a new name, especially when the names match. It is a separate variable that starts as a copy. Draw two boxes on the board, one in main and one in the method, and copy the value across at the call. Worksheet question 8’s lie is this misconception.

Misconception: A void method can fill in a variable for the caller

Students expect a method to “fill in” the variable it was given, as ParameterAsResult tries to. The copy and its new value vanish when the method ends. If the caller needs a primitive answer, the method must return it and the caller must store it.

Day 3 · Guided practice: Two copies in one program

  1. Slide 20 (pause and try). Students find every copy. Answer: 6 9. getGallons returns a copy of 3; main doubles its own copy to 6. fill receives a copy of 6, adds it to gallons (3 + 6 = 9), then sets its parameter to 0, which changes nothing outside the method.
  2. Worksheet question 3 (you’re the JVM) in pairs. Answer: A, 3 -1. unlock(3) returns on guess 3 with tries at 3. unlock(9) never matches: tries goes to 8, the loop finishes, and return -1; runs. Students who chose C saw that tries reaches 8 but missed which return ran.

Day 3 · Closure: Closure and exit ticket

Slide 21 lists the vocabulary; read it quickly as a check. Then slide 22: partners explain the difference between a mutator and an accessor, with a header for each, using the sentence starter (“A mutator changes the object and is usually void, but an accessor returns a copy of an instance variable’s value”). Give the exit ticket in the last few minutes; finish it at the start of the next class if needed. Score each question separately: question 1 checks return inside an if and call by value, question 2 void and non-void calls, and question 3 recognizing a correct mutator and non-void method. Re-teach the weakest one at the start of Topic 3.6.

Day 3 independent practice (homework)

Worksheet questions 4 (code tiles), 6 (you’re the compiler), 8 (two truths and a lie), and 9 (who am I?), about 15 minutes. Key points: in question 4 the decoy tile cost = coins - cost; changes only the parameter; in question 6 only method 3 compiles (it prints 3.0); in question 8 claim 3 is the lie.

Exit ticket

Question 1 · Multiple choice

What does this program print?

ExitTicketTrace.java
class TicketBooth
{
    private int tickets;

    public TicketBooth(int startTickets)
    {
        tickets = startTickets;
    }

    public void sell(int count)
    {
        if (count > tickets)
        {
            return;
        }
        tickets = tickets - count;
        count = 0;
    }

    public int getTickets()
    {
        return tickets;
    }
}

public class ExitTicketTrace
{
    public static void main(String[] args)
    {
        TicketBooth booth = new TicketBooth(10);
        int order = 4;
        booth.sell(order);
        booth.sell(8);
        System.out.println(order + " " + booth.getTickets());
    }
}
  1. 4 6
  2. 0 6
  3. 4 -2
  4. 0 -2
Check your reasoning

A. booth.sell(order): count starts as a copy of 4. 4 is not more than 10, so tickets becomes 6. Setting count to 0 changes only the copy, so order is still 4.

booth.sell(8): 8 is more than 6, so return; ends the method before the subtraction. tickets stays 6.

  • B thinks changing the parameter count changed order, but the method got a copy of the value.
  • C keeps running after return;, subtracting 8 from 6.
  • D makes both mistakes.

Question 2 · Multiple choice

A class Game has the methods public void addPoints(int p) and public int getPoints(), and g refers to a Game object. Which statement compiles?

  1. int x = g.addPoints(5);
  2. g.getPoints() = 10;
  3. System.out.println(g.addPoints(5));
  4. System.out.println(g.getPoints() + 5);
Check your reasoning

D. getPoints is non-void, so its call is an int value that can be used in an expression and printed. A and C use a void call as a value; addPoints returns nothing, so there is nothing to store or print, and it must be called on its own line: g.addPoints(5);. B assigns to a call, but a call is a value, not a variable; changing the points takes a mutator such as addPoints.

Question 3 · Multiple choice

A class Plant has one instance variable, private int height;. It needs grow, which takes an int number of centimeters and adds it to height, and isTallerThan, which takes an int limit and returns whether height is greater than the limit. Which pair of methods is correct?

  1. public int grow(int cm) { height = height + cm; } and public boolean isTallerThan(int limit) { return height > limit; }
  2. public void grow(int cm) { cm = height + cm; } and public boolean isTallerThan(int limit) { return height > limit; }
  3. public void grow(int cm) { height = height + cm; } and public boolean isTallerThan(int limit) { return height > limit; }
  4. public void grow(int cm) { height = height + cm; } and public int isTallerThan(int limit) { return height > limit; }
Check your reasoning

C. grow is a void mutator: it changes the instance variable and returns nothing. isTallerThan is non-void, and height > limit is a boolean, so the return type is boolean. Tested in a class with a constructor and a main, it prints false (12 is not more than 15), then true (17 is):

ExitPlant.java
class Plant
{
    private int height;

    public Plant(int startHeight)
    {
        height = startHeight;
    }

    public void grow(int cm)
    {
        height = height + cm;
    }

    public boolean isTallerThan(int limit)
    {
        return height > limit;
    }
}

public class ExitPlant
{
    public static void main(String[] args)
    {
        Plant fern = new Plant(12);
        System.out.println(fern.isTallerThan(15));
        fern.grow(5);
        System.out.println(fern.isTallerThan(15));
    }
}
  • A gives grow the return type int but never returns a value, so it does not compile (missing return statement).
  • B assigns to the parameter cm, a copy that vanishes when the method ends, so height never changes.
  • D returns a boolean from a method declared int, so it does not compile (boolean cannot be converted to int).