AP · Computer Science A · Anatomy of a Class

Writing Methods

14 min readUpdated December 1, 2026FreeAP Computer Science A, Class Creation

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

  1. What does every method header have that a constructor header never has?Show answerHide answer

    A return type, such as int, boolean or void.

  2. 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.

  3. A header reads public int getScore(). What must the body do before it finishes?Show answerHide answer

    Return an int value with a return statement.

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

For public double area(int w, int h), what type is the value of the call box.area(3, 4)?
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

Does a method compile if its body is if (x > 0) { return 1; } else { return 2; } and the return type is int?
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

Is public void reset() an accessor or a mutator?
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

Inside addOne, which object's level does isFull() check?
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.

  1. Step 1: Trace each call.

    CalllevelcapacityNote
    new Tank(50)050
    fill(30)305030 ≤ 50
    use(45)305045 > 30, no change
    fill(25)505055 capped at 50
    use(20)305020 ≤ 50
    Why

    Each void call changes level, and the next call starts from that new value.

  2. Step 2: Evaluate the prints.

    The first println runs after fill(25): getLevel() is 50 and isFull() is true. The second runs after use(20) and prints 30.

    Why

    A 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.

  1. Step 1: Choose the headers.

    spaceLeft takes nothing and gives a number: public int spaceLeft(). fillIfRoom takes an amount and answers yes or no: public boolean fillIfRoom(int amount).

    Why

    The return type follows from what the caller needs back.

  2. 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;
    }
    
    Why

    Both paths of fillIfRoom end in a return, so it compiles.

  3. Step 3: Trace.

    After fill(30), spaceLeft() is 20. 15 ≤ 20, so level becomes 45 and a is true. Now spaceLeft() is 5; 10 > 5, so b is false and level stays 45.

    Why

    The 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.

  1. Step 1: Find the open path.

    For age 20 or more, both conditions are false and the body ends with no return.

    Why

    The else if has no final else, so it can be skipped.

  2. Step 2: Test each option.

    B returns "adult" on that path. A makes return "child"; an error in a void method. C leaves the open path. D still ends in an if with no else; the compiler does not reason that the conditions cover every age.

    Why

    Only an unconditional return closes 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());
  1. Step 1: Trace the first two calls.

    score(70) makes points 70, below 100, so lives stays 3. hit() makes lives 2.

  2. 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; }?
  1. 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

  1. Recall Which header fits a method that takes a String and an int and gives back true or false?
  • 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 back true or false.
  • B has no return type, which only a constructor may omit.
  • C leaves out the parameter types.
  1. Recall Name the return type of a method that returns no value.
Show answer

Answer: void

Marking points:

  • A void method can use return; but never return with a value.
  1. 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 return is skipped; 150 > 90 returns "medium".
  • 151 > 150 returns "large" at once.
  1. 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 spend returns false and cash stays 20.
  • earn(3) adds 36, making 56; spend(25) returns true and leaves 31.
  1. Exam-style The method should return the mean of the int instance variables s1, s2 and s3 as a double. 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 / 3 is int division: 23 / 3 is 7, which only then becomes 7.0.
  • The fix is return total / 3.0;, which returns 7.666….
  1. Exam-style A class has private int charge; and a method public boolean isLow() that returns charge < 20. Which body for public 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 isLow is read as a variable that does not exist.
  • B has no return when the charge is not low, so it does not compile.
  • D calls a method on charge, an int, which has no methods.
  1. 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 advance sets x to 3 × 2 − 1 = 5; the second sets it to 5 × 2 − 1 = 9.
  • getX() + twice() adds two ints, 9 + 18, so it prints 27, not "918".
  1. Apply A class has the method public double cost(int qty, double each), and obj refers 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 double return value in an int, which Java does not allow without a cast.
  • C swaps the arguments, so 2.5 would go into the int parameter qty.
  • 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-void method needs a return on every path; return ends the method at once.
  • A void method changes state and cannot be used as a value.
  • Calling isFull() inside the class runs it on the same object.

Keep learning

Prerequisites: Writing Constructors

Explore AP Computer Science A tutoring →

View the full Computer Science A syllabus →

More in this unit

Class Creation

All Anatomy of a Class notes

Part of Novark's AP Computer Science A notes