AP Computer Science A · Study guide

Writing Methods with Primitive Values

AP® Computer Science A · Class Creation

Writing Methods With Primitive Values

How to write the methods that give objects their behaviors: void and non-void headers, returning values, what the return statement does to the flow of control, accessor and mutator methods, and how primitive parameters receive copies of their arguments.

Big Picture

Methods define an object's behaviors. A void method does not return a value, and its header contains the keyword void before the method name. A non-void method returns a single value, and its header includes the return type in place of void; a return expression compatible with that type is evaluated and its value is returned, which is called return by value. The return keyword sends control back to the caller immediately. Accessor methods let other classes obtain a copy of an instance or class variable; mutator methods change those values and are often void. Primitive arguments are copied into parameters, so changing a parameter never affects the caller.

1Method Headers: void and Non-void

A method header states who may call the method, what it gives back, its name, and what it needs. A void method does not return a value; its header contains the keyword void before the method name, as in public void recharge(). A non-void method returns a single value; its header includes the return type in place of void, as in public int minutesLeft(int drainPerMinute).

Instance methods, the ones that work with a particular object's data, are written without the keyword static. Inside their bodies they can use the object's instance variables directly by name, because each call runs on one specific object: charge inside getCharge means the charge of whichever battery the method was called on.

Choosing between void and non-void is a design decision. If the method's purpose is to change the object, such as using up charge, it is usually void. If its purpose is to answer a question, such as how many minutes remain, it is non-void and returns the answer. Methods that both change the object and return a result exist, but keeping the two roles separate makes classes easier to understand.

Figure 1. A void method's header contains the keyword void before the method name. A non-void method's header includes the return type in place of void.
Kind of methodHeaderTypical body
voidpublic void recharge()Changes state; no return value
Non-voidpublic int minutesLeft(int drainPerMinute)Computes and returns a single value
Accessorpublic int getCharge()return charge;
Mutatorpublic void use(int amount)Updates instance variables, applying rules

2Returning a Value

In non-void methods, a return expression compatible with the return type is evaluated, and the value is returned. This is referred to as return by value: the caller receives the value itself, which it can store, print, or use in an expression. A method declared to return int must return an int (or a value that converts to one automatically); returning a String from it does not compile.

A non-void method must return a value on every path through its body. If some combination of conditions could reach the end of the method without a return, the compiler reports a missing return statement. Ending such methods with a final return that covers all remaining cases is a reliable habit.

Worked Example 1 Return by value

Using a Returned Value

Predict the output.

Using the same Battery class
public class Battery
{
    private int charge;
    private int cycles;

    public Battery()
    {
        charge = 100;
        cycles = 0;
    }

    public int getCharge()
    {
        return charge;
    }

    public boolean isLow()
    {
        return charge < 20;
    }

    public void use(int amount)
    {
        charge = charge - amount;
        if (charge < 0)
        {
            charge = 0;
        }
    }

    public void recharge()
    {
        charge = 100;
        cycles++;
    }

    public int getCycles()
    {
        return cycles;
    }

    public int minutesLeft(int drainPerMinute)
    {
        return charge / drainPerMinute;
    }
}
Output
18
21
  1. 1After use(28), the charge is 72.
  2. 2minutesLeft(4) evaluates charge / drainPerMinute = 72 / 4 = 18 and returns that value, which is stored in left.
  3. 3Returned values in an expression. 72 / 5 = 14 (integer division) and 72 / 10 = 7; 14 + 7 = 21.
Result: The output is 18 and 21. In a non-void method, a return expression compatible with the return type is evaluated and its value is returned: return by value.
Worked Example 2 Missing return

Every Path Must Return a Value

Explain the compile error, then fix it.

Code that does not compile
public static String sizeLabel(int ml)
{
    if (ml < 250)
    {
        return "small";
    }
    else if (ml < 500)
    {
        return "medium";
    }
}
Fixed
public static String sizeLabel(int ml)
{
    if (ml < 250)
    {
        return "small";
    }
    else if (ml < 500)
    {
        return "medium";
    }
    return "large";
}
Output
small
medium
large
  1. 1The problem. For 500 ml or more, neither condition is true and the method reaches its end with no value to return.
  2. 2The fix. A final return "large"; covers every remaining case.
Result: The first version does not compile; the fixed version prints small, medium, large. A non-void method must return a value on every possible path.
Common Mistake 1 · Printing Instead of Returning

A method whose job is to compute a value should return it, not print it. Printing shows the value on the screen, but the calling code cannot use it in further calculations. Keep printing in the code that calls the method.

3The return Statement and Flow of Control

The return keyword is used to return the flow of control to the point where the method or constructor was called. Any code that is sequentially after a return statement will never be executed, and Java rejects statements that could never run as unreachable.

Executing a return statement inside a selection or iteration statement will halt the statement and exit the method or constructor. This makes early returns a clear way to stop searching as soon as an answer is found, such as returning the first divisor of a number, with a final return after the loop for the case where nothing was found.

Figure 2. Executing a return statement inside a selection or iteration statement halts the statement and exits the method.
Fact about returnConsequence
Returns control to the point where the method was calledThe caller continues with the returned value
Code sequentially after it never runsJava reports such code as an unreachable statement
Inside a loop or if, it exits the whole methodUse it to stop as soon as the answer is known
A non-void method must return on every pathOtherwise: missing return statement
Worked Example 3 Early return

Leaving a Loop With return

Predict the output.

Code
public static int smallestDivisor(int n)
{
    for (int d = 2; d < n; d++)
    {
        if (n % d == 0)
        {
            return d;
        }
    }
    return n;
}
Output
7
97
2
  1. 191. No divisor among 2 to 6; at 7, 91 % 7 == 0, so return 7 ends the method immediately (Figure 2).
  2. 297. No d divides it, so the loop finishes and the final return n gives 97: 97 is prime.
  3. 312. The very first check succeeds: 2.
Result: The output is 7, 97, 2. A return inside a loop halts the loop and exits the method, which is a clean way to stop as soon as the answer is known.
Worked Example 4 Unreachable code

A Statement After return

Explain the compile error.

Code that does not compile
public static int doubled(int x)
{
    return x * 2;
    System.out.println("doubling");
}
  1. 1return leaves the method. Any code sequentially after it can never run.
  2. 2Java rejects such code with an "unreachable statement" error.
  3. 3Fix. Put the print before the return, or remove it.
Result: The method does not compile. Any code that is sequentially after a return statement will never be executed, and Java reports it as unreachable.
Common Mistake 2 · Returning Inside a Loop Too Soon

A return inside the loop body that runs on the first pass, for example in an else branch, ends the method before the remaining values are checked. Return early only when the answer is certain; otherwise let the loop continue and return after it.

4Accessor and Mutator Methods

An accessor method allows objects of other classes to obtain a copy of the value of instance variables or class variables. An accessor method is a non-void method, such as getCharge() or isLow(). Because it returns a copy of a primitive value, the caller cannot use it to change the object's data.

A mutator (modifier) method is a method that changes the values of the instance variables or class variables. A mutator method is often a void method, such as use(int amount) or recharge(). Mutators are where a class enforces its rules: use never lets the charge drop below 0, so no sequence of calls can produce an invalid battery.

Not every instance variable needs both kinds of method. A class provides an accessor when other classes need to read a value and a mutator only when they should be able to change it. The battery offers getCycles() but no way to set the cycle count directly, because cycles should increase only when the battery is actually recharged.

Figure 3. An accessor method lets other classes obtain a copy of an instance or class variable's value. A mutator method changes those values and is often void.
Callcharge beforeEffectcharge after
new Battery()constructor sets 100100
use(45)100100 − 4555
use(40)5555 − 4015
recharge()15set to 100, cycles 1100
use(130)100−30, clamped0
Worked Example 5 Accessors and mutators

Using a Battery Object

The Battery class is given. Predict the output.

The Battery class and a short program
public class Battery
{
    private int charge;
    private int cycles;

    public Battery()
    {
        charge = 100;
        cycles = 0;
    }

    public int getCharge()
    {
        return charge;
    }

    public boolean isLow()
    {
        return charge < 20;
    }

    public void use(int amount)
    {
        charge = charge - amount;
        if (charge < 0)
        {
            charge = 0;
        }
    }

    public void recharge()
    {
        charge = 100;
        cycles++;
    }

    public int getCycles()
    {
        return cycles;
    }

    public int minutesLeft(int drainPerMinute)
    {
        return charge / drainPerMinute;
    }
}
Output
15 true
100 1
0 true
  1. 1Mutators change state. use(45) and use(40) lower the charge from 100 to 15.
  2. 2Accessors report it. getCharge() returns 15 and isLow() returns true, since 15 < 20.
  3. 3recharge() sets the charge to 100 and counts a cycle.
  4. 4use(130) would go negative, so the mutator clamps the charge at 0.
Result: The output is 15 true, 100 1, and 0 true. Accessors return values without changing the object; mutators change the instance variables, applying the class's rules.

5Methods With Parameters

Methods with parameters receive values through those parameters and use those values in accomplishing the method's task. use(int amount) needs to know how much charge to remove; minutesLeft(int drainPerMinute) needs the rate of use. Parameters make a method general, so one method handles every amount or rate.

When an argument is a primitive value, the parameter is initialized with a copy of that value. Changes to the parameter have no effect on the corresponding argument. A method can therefore freely change its own parameters as working variables, but it cannot pass a result back through them; results go back through the return value or through changes to the object's instance variables.

Figure 4. When an argument is a primitive value, the parameter is initialized with a copy of that value. Changes to the parameter have no effect on the corresponding argument.
Worked Example 6 Parameters are copies

A Method Cannot Change the Caller's Variable

Predict the output.

Code
public static int addBreak(int m)
{
    m = m + 15;
    return m;
}
Output
40
55
  1. 1The call copies 40 into the parameter m.
  2. 2Inside the method m becomes 55 and is returned.
  3. 3minutes is unchanged, because only the copy was modified (Figure 4). The caller receives the new value through the return value instead.
Result: The output is 40 and 55. When an argument is a primitive value, changes to the parameter have no effect on the argument; to pass a result back, return it.
Common Mistake 3 · Expecting a Method to Update the Caller's Variable

After addBreak(minutes), the variable minutes still has its old value; only the parameter changed. Capture the result instead: minutes = addBreak(minutes);.

6Writing Methods Well

Good methods have one clear job, a name that describes it, and a header that tells callers exactly what they need and what they will get back. Accessors are named for what they report, often starting with get or is; mutators are named for the change they make. Keeping each method small makes it easy to test with a few calls.

When writing a method body, decide first whether the method should change the object, report on it, or compute something from its parameters, and write the header accordingly. Then check every path: does each one return a value of the right type, and does each change keep the object's state valid?

Common Mistake 4 · Returning the Wrong Type

A method declared public boolean isLow() must return a boolean, such as charge < 20, not the charge itself. The compiler rejects a return expression that is not compatible with the declared return type.

Four Habits for Writing Methods

1. void or a Type

The header says whether a value comes back.

2. Return on Every Path

And nothing after a return can run.

3. Accessors Report, Mutators Change

Enforce the class's rules in mutators.

4. Parameters Are Copies

Send results back with return.

Core Synthesis

A void method does not return a value, and its header contains the keyword void before the method name; a non-void method returns a single value, and its header includes the return type in place of void. In non-void methods, a return expression compatible with the return type is evaluated and returned, which is return by value. The return keyword returns the flow of control to the point where the method was called; code after a return never executes, and a return inside a selection or iteration statement exits the method. An accessor method, which is non-void, lets objects of other classes obtain a copy of an instance or class variable's value; a mutator method changes those values and is often void. Methods with parameters use the received values to accomplish their task, and when an argument is a primitive value, the parameter is a copy, so changes to it have no effect on the argument.