Java Methods β Definition, Parameters, Return Types, Overloading
A method is a named, parameterised, reusable block of code attached to a class. Every Java program runs by calling methods β starting with public static void main(String[] args). The full signature is name + parameter types (return type is not part of the signature).
Anatomy of a method
public static int add (int a, int b) throws ArithmeticException {
// β β β β β β β
// access modifier return name parameters checked exceptions body
return a + b;
}
Static vs instance
public class Calculator {
public static int add(int a, int b) { return a + b; } // no object needed
public int subtract(int a, int b) { return a - b; } // needs an instance
}
Calculator.add(3, 4); // β
static β call via class
new Calculator().subtract(7, 2); // β
instance β needs new
Use static when the method doesn't depend on instance state β utility functions, factories, the canonical main.
Parameters: by value
Java is always pass-by-value. For primitives, the value is the number. For objects, the value is the reference β the method can mutate the object via that reference, but reassigning the parameter doesn't change the caller's variable:
void mutate(StringBuilder sb) { sb.append(" world"); } // β
caller sees this
void reassign(StringBuilder sb) { sb = new StringBuilder("nope"); } // β caller doesn't
Varargs (...) β variable number of arguments
public static int sum(int... nums) {
int total = 0;
for (int n : nums) total += n;
return total;
}
sum(); // 0
sum(1, 2, 3); // 6
sum(new int[]{1,2,3}); // 6 β also works with an array
Varargs must be the last parameter and there can be only one per method.
Overloading
Two methods with the same name but different parameter lists. The compiler picks the best match at compile time:
public void log(String msg) { ... }
public void log(String msg, Throwable t) { ... }
public void log(int code, String msg) { ... }
Overloading by return type alone is illegal β return type is not part of the signature.
Method references and lambdas (Java 8+)
// Lambda
list.forEach(s -> System.out.println(s));
// Method reference β same thing, shorter
list.forEach(System.out::println);
// Methods as values
Function<String, Integer> len = String::length;
int n = len.apply("hello"); // 5
Recursion
public static long factorial(int n) {
if (n <= 1) return 1; // base case β must exist
return n * factorial(n - 1); // recursive case
}
Java doesn't optimise tail calls β deep recursion will blow the stack. Convert to a loop for anything more than a few thousand frames.
Methods vs constructors
| Constructor | Method | |
|---|---|---|
| Name | Same as the class | Anything (camelCase) |
| Return type | None (not even void) | Required |
| Inherited | No β but called via super() | Yes |
| Purpose | Initialise an object | Do work |
All sub-topics
mainmethod β the entry point- Parameters & pass-by-value
- Varargs (
...) - Overloading
- Static methods
- Recursion
equalsandhashCodetoString
Common mistakes
- Mutating a parameter and expecting the caller to see it β for primitives and immutable types, the caller never sees changes.
- Overriding without
@Overrideβ a typo (e.g.equals(MyClass o)instead ofequals(Object o)) creates a new method instead of overriding the inherited one.@Overridecatches this at compile time. - Returning
nullfor a "no result" β useOptional<T>for clear intent. - Method too long β if it doesn't fit on one screen, split it. Each method should do one thing.
Try it & related tools
Run any method in the Java Online Compiler. The printf tutorial walks through one of the most-used overloaded methods in Java.