Java Methods
Reusable blocks of code with names. The atoms of behavior in Java.
Defining a method
Method anatomy
public static int add(int a, int b) { return a + b; } // ↑ ↑ ↑ ↑ // | | | parameters // | | method name // | return type // modifiers
Calling a method
Use it
public class Calculator { public static int add(int a, int b) { return a + b; } public static void main(String[] args) { int result = add(5, 3); System.out.println(result); // 8 } }
Return types
Every method declares what it returns:
- A specific type —
int,String,List<User>, etc. void— returns nothing
Returning vs. void
public static String greet(String name) { return "Hello, " + name; } public static void printGreeting(String name) { System.out.println("Hello, " + name); // no return needed }
Parameters
Methods can take any number of parameters — including zero. Java passes primitives by value (a copy) and objects by reference (a copy of the reference).
Pass-by-value mechanics
public static void modify(int x) { x = 100; // modifies local copy only } public static void main(String[] args) { int n = 5; modify(n); System.out.println(n); // still 5 }
Method overloading
Multiple methods with the same name but different parameter lists. Java picks the right one based on what you pass:
Overloading
public static int add(int a, int b) { return a + b; } public static double add(double a, double b) { return a + b; } public static int add(int a, int b, int c) { return a + b + c; } add(5, 3); // uses int version add(5.0, 3.0); // uses double version add(1, 2, 3); // uses three-arg version
Variable arguments (varargs)
Accept any number of arguments of the same type using ...:
varargs
public static int sum(int... numbers) { int total = 0; for (int n : numbers) total += n; return total; } sum(); // 0 sum(1, 2, 3); // 6 sum(10, 20, 30, 40, 50); // 150
Recursion
A method that calls itself. Powerful for problems with self-similar structure.
Factorial
public static int factorial(int n) { if (n <= 1) return 1; // base case return n * factorial(n - 1); // recursive case } factorial(5); // 120
Always have a base case
Without one, recursion never stops and you get a
StackOverflowError.