Methods: How to Write Them
Skill 2.CSkill 3.CSkill 3.DSkill 4.B
Big idea: A method either does something (void) or computes and hands back one value (non-void). return ends the method immediately.
- Develop code to define behaviors of an object through methods written in a class using primitive values and determine the result of calling these methods.
Accessors and mutators
An accessor (getter) returns information about the object without changing it. A mutator (setter or modifier) changes instance variables; it is often void.
public int getScore() { return score; } // accessor
public void addPoints(int p) { score += p; } // mutator
public boolean isWinning() { return score > 100; }return ends the method
When return runs, control goes straight back to the caller. Code after it in that method never runs. Every path through a non-void method must reach a return.
static int firstNegative(int a, int b, int c) {
if (a < 0) return a;
if (b < 0) return b;
if (c < 0) return c;
return 0;
}Using themSystem.out.println(firstNegative(4, -2, -7));
System.out.println(firstNegative(1, 2, 3));Output-2 0
Classic bug: returning too early
This method is supposed to check whether all values are positive, but the else returns after looking at only the first one.
static boolean allPositiveBuggy(int[] v) {
for (int x : v) {
if (x <= 0) return false;
else return true; // stops after the first value
}
return true;
}
static boolean allPositive(int[] v) {
for (int x : v) {
if (x <= 0) return false;
}
return true; // only after checking every value
}Using themint[] nums = {5, -1};
System.out.println(allPositiveBuggy(nums));
System.out.println(allPositive(nums));Outputtrue false
Primitive parameters get copies
Changing a primitive parameter inside a method has no effect on the caller's variable.
Methodsstatic void tryToDouble(int x) { x = x * 2; }Using themint n = 5;
tryToDouble(n);
System.out.println(n);Output5- A
voidmethod returns nothing; a non-void method returns one value of its declared type. returnimmediately sends control back to the caller.- Accessors return information; mutators change state.
- A primitive parameter is a copy; changing it doesn't change the argument.
- Returning in the loop's
elsebranch stops after the first element. - Every path through a non-void method must return a value, or it won't compile.
- On FRQs, return the value; don't print it unless the question says to.
What's wrong?
public int bigger(int a, int b) {
if (a > b) return a;
else if (b > a) return b;
}Show answer
It doesn't compile: when a == b no return runs. Change the else if to else.