These notes recap Topic 3.5. For the full explanations and worked examples, read the study guide.
Recap
- A void method returns nothing. A non-void method returns a single value whose type is in the header (return by value).
returnhands control back to the caller. Code after it on the same path never runs; areturninside anifor a loop exits the whole method.- A non-void method must return on every path.
- An accessor returns a copy of an attribute’s value (non-void). A mutator changes attributes (often void).
- For a primitive argument the parameter is a copy. Changing the parameter does not change the argument.
- Preconditions are the initial conditions a method needs to work as described.
Key relationships
| Method kind | Header pattern | Typical body |
|---|---|---|
| Accessor | public int getCoins() |
return coins; |
| Mutator | public void addCoins(int amount) |
coins += amount; |
| Mutator with result | public boolean spend(int amount) |
test, change, return true / return false |
| Calculation | public int coinsWithBonus(int percent) |
return coins + coins * percent / 100; |
| Helper | private boolean isValid(int p) |
return p > 0; |
Compile errors to recognise
| Message | Cause |
|---|---|
missing return statement |
A path through a non-void method has no return |
unreachable statement |
Code placed after a return in the same block |
incompatible types: possible lossy conversion from double to int |
Returning a double from an int method |
incompatible types: unexpected return value |
return x; inside a void method |
Worked reminder
Wallet(40); addCoins(10) makes 50; spend(70) returns false and leaves 50; spend(30) returns true and leaves 20; coinsWithBonus(15) is 20 + 20 * 15 / 100 = 23 and does not change the 20. With int n = 5; h.addTen(n); the value of n is still 5; with n = h.addTenAndReturn(n); it becomes 15. And isPrime(15) returns false the moment d reaches 3, without trying d = 4.
Mistakes to avoid
- Forgetting the final
returnafter anif/else ifchain. - Putting a statement after a
return. - Expecting a void method to give back a value.
- Expecting a primitive parameter to alter the caller’s variable.
- Using integer division where a decimal was wanted (for example
a / bwith twointvalues).
Quick self-check
- What does
public void f(int x) { x = 0; }do to the caller’s argument? Answer: nothing; x is a copy. - A method contains
for (...) { if (cond) { return 1; } }thenreturn 0;. When does it return 0? Answer: only if the condition was never true in the loop. - Is
public int getX()an accessor or a mutator? Answer: an accessor. - Give a sensible precondition for
int average(int total, int count). Answer:count > 0.