ACSA Exam Prep
Unit 3 · Class Creation · Topic 3.5

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.

Learning objectives
  • 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.

Methods
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 them
System.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.

Methods
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 them
int[] nums = {5, -1};
System.out.println(allPositiveBuggy(nums));
System.out.println(allPositive(nums));
Output
true
false

Primitive parameters get copies

Changing a primitive parameter inside a method has no effect on the caller's variable.

Methods
static void tryToDouble(int x) { x = x * 2; }
Using them
int n = 5;
tryToDouble(n);
System.out.println(n);
Output
5
Key points
  • A void method returns nothing; a non-void method returns one value of its declared type.
  • return immediately 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.
Watch out
  • Returning in the loop's else branch 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.
Quick check
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.