Topic 3.5 — Methods: How to Write Them

Goal: write method headers and bodies with correct return types, parameters, and control flow, and understand how methods help with abstraction, reuse, and organization.

The big idea

A method is a named block of code that performs a task. Writing good methods means designing clear inputs (parameters), clear outputs (return values), and a body that does exactly what the header promises.

Method header anatomy

Part Example Meaning
access public who can use it
return type int / boolean / void what it gives back
name calcArea what it’s called
parameters (int w, int h) inputs to the method

Example: a method that returns a value

public int calcArea(int width, int height) {
  int area = width * height;
  return area;
}
  • Return type is int, so it must return an int.
  • return ends the method immediately.

Void methods

A void method does a task but does not return a value.

public void reset() {
  value = 0;
}

You can still use return; in a void method to exit early, but it returns nothing.

Return-type mistakes

  • If return type isn’t void, every path must return a value.
  • Don’t return the wrong type (Java will error).
// Bug: missing return when x <= 0
public int f(int x) {
  if (x > 0) return x;
  // ❌ no return here
}

Parameters are local variables

  • Parameters behave like variables inside the method.
  • Changes to primitive parameters (int, double, boolean) do not change the original variable outside.
  • You can use parameters to avoid repeated code.
public boolean isEven(int n) {
  return n % 2 == 0;
}

Writing methods: a simple workflow

  1. Decide the method’s job (1 sentence).
  2. Pick parameter types/names (inputs).
  3. Pick return type (output) or void.
  4. Write the body using variables + selection/iteration.
  5. Check: do all paths return (if needed)?

Quick self-check

  1. What are the 4–5 main parts of a method header?
  2. What does void mean?
  3. Why must every path return a value for a non-void method?
  4. Are parameters local variables?
  5. Write a method max(int a, int b) that returns the larger value.

← Back to Unit 3 topics