Methods are how you name ideas, avoid repetition and make code testable.
A method is a named block of code with parameters and a return type:
static double area(double width, double height) {
return width * height;
}The parts are: modifiers (static here, meaning it belongs to the class), the return type (double, or void for nothing), the name, and a parameter list. A non-void method must return a value on every path — the compiler checks that.
Overloading means several methods share a name but differ in parameter types or counts, e.g. print(int) and print(String). The compiler picks the best match from the argument types at compile time. The return type alone can't distinguish overloads.
Varargs let a method accept any number of arguments: static int sum(int... values); inside, values is an int[].
Java is strictly pass-by-value. For primitives the method receives a copy of the number. For objects it receives a copy of the reference: the method can call methods on the object and mutate it, and the caller sees those changes, but assigning a new object to the parameter has no effect outside.
Good methods are short, do one thing and have a name that says what: calculateTotal, isValid, findUserById. Boolean-returning methods usually start with is, has or can. If a method needs many parameters, that's a hint to group them into a class or record.
Local variables live only during a call. Each call gets a fresh set on the stack, which is also why recursion (a method calling itself) works.
Example
import java.util.Arrays;
public class Methods {
static int sum(int... values) { // varargs
int total = 0;
for (int v : values) total += v;
return total;
}
static String describe(int n) { return "int " + n; }
static String describe(String s) { return "text " + s; } // overload
static void tryToChange(int x, int[] arr) {
x = 99; // changes the local copy only
arr[0] = 99; // mutates the caller's array
arr = new int[]{-1}; // rebinds the local reference only
}
public static void main(String[] args) {
System.out.println(sum(1, 2, 3) + " " + describe(7) + " " + describe("hi")); // 6 int 7 text hi
int x = 1;
int[] arr = {1};
tryToChange(x, arr);
System.out.println(x + " " + Arrays.toString(arr)); // 1 [99]
}
}Remember
- Signature = name + parameter types; overloads differ in parameters
- Java passes everything by value — for objects, the value is a reference
- Keep methods small, single-purpose and well named
Watch out for
- Expecting a method that reassigns its parameter (
list = new ArrayList<>()) to change the caller's variable.