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 anint. returnends 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
- Decide the method’s job (1 sentence).
- Pick parameter types/names (inputs).
- Pick return type (output) or
void. - Write the body using variables + selection/iteration.
- Check: do all paths return (if needed)?
Quick self-check
- What are the 4–5 main parts of a method header?
- What does
voidmean? - Why must every path return a value for a non-void method?
- Are parameters local variables?
- Write a method
max(int a, int b)that returns the larger value.