Defining Methods
Packaging behavior into reusable methods — parameters, return types, and the static keyword.
2 min read
A method is a named, reusable block of code — Java's equivalent of what other languages call a function, though in Java every method belongs to a class. Breaking logic into well-named methods is what keeps a program readable as it grows past a few dozen lines.
Anatomy of a method
public static int add(int a, int b) {
return a + b;
}public— an access modifier controlling who can call this method (more on this in a later lesson).static— means the method belongs to the class itself, not to an instance of it; you can calladd(2, 3)without creating an object first.int— the return type: the type of value this method hands back. Usevoidif the method doesn't return anything.add— the method name, conventionallycamelCase.(int a, int b)— the parameters: named, typed inputs the caller supplies.return a + b;— sends the result back to the caller. Execution stops at thereturnstatement.
Calling a method
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int sum = add(5, 7);
System.out.println(sum); // 12
}
}add is called with two arguments, 5 and 7, which are bound to the parameters a and b inside the method. Parameters are local to the method — they don't exist outside it.
void methods
A method that performs an action but doesn't need to hand back a value uses void as its return type, and simply omits (or uses a bare) return:
public static void greet(String name) {
System.out.println("Hello, " + name + "!");
}Parameters are passed by value
Java always passes arguments by value — the method receives a copy. For primitives, that means changes inside the method never affect the caller's variable:
public static void increment(int x) {
x = x + 1; // only changes the local copy
}
int number = 5;
increment(number);
System.out.println(number); // still 5For object references (like arrays or custom objects), the reference is copied — so the method can't reassign the caller's variable to a different object, but it can modify the object the reference points to, since both the original and the copy point at the same object in memory. That distinction matters a lot once you start passing arrays and custom objects around, and it's worth experimenting with directly rather than just memorizing.
Test what you just learned
4 quick questions. Get all of them right to unlock the next lesson.
You can take the quiz without an account — logging in just lets your result count toward your progress.