Methods
Parameters, return values, overloading, varargs, pass-by-value, scope and recursion.
As programs grow, you do not want one giant main. A method is a named, reusable block of code that performs one task. You have already used many: System.out.println, Math.max, name.length(). Now you will write your own.
Methods let you:
- Reuse logic instead of copy-pasting it.
- Name ideas (
calculateTaxsays more than ten lines of arithmetic). - Test small pieces independently.
Defining and calling a method#
Anatomy of a method declaration:
staticmeans the method belongs to the class, somain(also static) can call it directly. You will learn about instance methods in the OOP lessons.- The return type says what the method gives back;
voidmeans nothing. - Parameters are inputs, each with a type and a name. The values you pass when calling are the arguments.
Returning values#
A method with a non-void return type must return a value of that type on every path:
return ends the method immediately. That enables guard clauses: handle special cases first and return early, keeping the main logic unindented:
Parameters are passed by value#
Java always passes a copy of each argument into the method. For primitives this means the method cannot change the caller's variable:
For objects and arrays, the value copied is the reference (the address). Both copies point to the same array, so changes to its contents are visible to the caller. But assigning a new array to the parameter only changes the local copy. This distinction, "pass-by-value of references", is a favourite interview question.
Method overloading#
Several methods can share a name if their parameter lists differ in number, type or order of parameters:
The compiler picks the best match from the argument types at compile time. The return type alone cannot distinguish overloads.
Varargs: any number of arguments#
Declare Type... name as the last parameter to accept zero or more values. Inside the method it is an array:
String.format, printf and List.of all use varargs.
Scope: where variables live#
A variable exists only inside the block { } where it is declared:
Parameters and local variables are created fresh on each call and disappear when the method returns. Two methods can each have their own x without interfering.
Recursion: methods that call themselves#
A recursive method solves a problem by calling itself on a smaller version of the same problem. It needs:
- A base case that returns without recursing.
- A recursive case that moves towards the base case.
How factorial(4) unfolds:
Every call takes space on the call stack. Recurse too deeply, or forget the base case, and you get a StackOverflowError. Many recursive problems (factorial, sums) are simpler as loops; recursion shines for naturally recursive structures such as trees, folders and divide-and-conquer algorithms. Note that this naive fib recomputes the same values exponentially many times, so it becomes very slow for large n.
Designing good methods#
- Do one thing. If you need "and" to describe it (
validateAndSaveAndEmail), split it. - Name with verbs:
calculateTotal,isValid,printReport. Boolean methods often start withis,hasorcan. - Keep them short. A method that fits on one screen is easier to understand.
- Prefer returning values over printing inside the method; the caller can then decide what to do with the result.
- Limit parameters. More than three or four is a hint to group them into an object.
A worked example#
%-6s prints a string left-aligned in 6 characters and %c prints a char.
Common mistakes#
- Forgetting to use the return value:
max(3, 8);on its own line computes 8 and throws it away. - A missing
returnon some path: the compiler reportsmissing return statement. - Expecting a method to change a primitive argument.
- Calling an instance (non-static) method from
static mainwithout an object:non-static method cannot be referenced from a static context.
What's next#
Methods let you organise logic. Next we store many values in one variable with arrays.
Check your understanding
Quick quiz
1.What does this print?
static void bump(int x) { x = x + 1; }...int n = 5; bump(n); System.out.println(n);2.Which pair of methods is a valid overload?
3.What is missing from a recursive method that causes a
StackOverflowError?
Finished reading?
Mark this lesson complete to track your progress.