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.
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.
void before the method name. A non-void method's header includes the return type in place of void.| Kind of method | Header | Typical body |
|---|---|---|
| void | public void recharge() | Changes state; no return value |
| Non-void | public int minutesLeft(int drainPerMinute) | Computes and returns a single value |
| Accessor | public int getCharge() | return charge; |
| Mutator | public 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.
Using a Returned Value
Predict the output.
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;
}
}
18
21
- 1After
use(28), the charge is 72. - 2
minutesLeft(4)evaluatescharge / drainPerMinute= 72 / 4 = 18 and returns that value, which is stored inleft. - 3Returned values in an expression. 72 / 5 = 14 (integer division) and 72 / 10 = 7; 14 + 7 = 21.
Every Path Must Return a Value
Explain the compile error, then fix it.
public static String sizeLabel(int ml)
{
if (ml < 250)
{
return "small";
}
else if (ml < 500)
{
return "medium";
}
}
public static String sizeLabel(int ml)
{
if (ml < 250)
{
return "small";
}
else if (ml < 500)
{
return "medium";
}
return "large";
}
small
medium
large
- 1The problem. For 500 ml or more, neither condition is true and the method reaches its end with no value to return.
- 2The fix. A final
return "large";covers every remaining case.
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.
return statement inside a selection or iteration statement halts the statement and exits the method.| Fact about return | Consequence |
|---|---|
| Returns control to the point where the method was called | The caller continues with the returned value |
| Code sequentially after it never runs | Java reports such code as an unreachable statement |
| Inside a loop or if, it exits the whole method | Use it to stop as soon as the answer is known |
| A non-void method must return on every path | Otherwise: missing return statement |
Leaving a Loop With return
Predict the output.
public static int smallestDivisor(int n)
{
for (int d = 2; d < n; d++)
{
if (n % d == 0)
{
return d;
}
}
return n;
}
7
97
2
- 191. No divisor among 2 to 6; at 7,
91 % 7 == 0, soreturn 7ends the method immediately (Figure 2). - 297. No
ddivides it, so the loop finishes and the finalreturn ngives 97: 97 is prime. - 312. The very first check succeeds: 2.
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.A Statement After return
Explain the compile error.
public static int doubled(int x)
{
return x * 2;
System.out.println("doubling");
}
- 1
returnleaves the method. Any code sequentially after it can never run. - 2Java rejects such code with an "unreachable statement" error.
- 3Fix. Put the print before the
return, or remove it.
return statement will never be executed, and Java reports it as unreachable.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.
| Call | charge before | Effect | charge after |
|---|---|---|---|
| new Battery() | constructor sets 100 | 100 | |
| use(45) | 100 | 100 − 45 | 55 |
| use(40) | 55 | 55 − 40 | 15 |
| recharge() | 15 | set to 100, cycles 1 | 100 |
| use(130) | 100 | −30, clamped | 0 |
Using a Battery Object
The Battery class is given. Predict the output.
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;
}
}
15 true
100 1
0 true
- 1Mutators change state.
use(45)anduse(40)lower the charge from 100 to 15. - 2Accessors report it.
getCharge()returns 15 andisLow()returnstrue, since 15 < 20. - 3
recharge()sets the charge to 100 and counts a cycle. - 4
use(130)would go negative, so the mutator clamps the charge at 0.
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.
A Method Cannot Change the Caller's Variable
Predict the output.
public static int addBreak(int m)
{
m = m + 15;
return m;
}
40
55
- 1The call copies 40 into the parameter
m. - 2Inside the method
mbecomes 55 and is returned. - 3
minutesis unchanged, because only the copy was modified (Figure 4). The caller receives the new value through the return value instead.
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?
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.
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.