Imagine you're building an application that sends notifications. At three different points in your code, you need to format a message, add a timestamp, and pass it to a delivery service. Without methods, you copy those fifteen lines of logic three times. When a bug surfaces in the formatting, you fix it in one place and forget the other two.
Methods solve this, not just as a convenience, but as a fundamental mechanism for organising computation. A method is a named, reusable sequence of instructions. Call it from anywhere, pass in what it needs, get back what it computed. The JVM has a specific structure for making this work at runtime: the call stack.
The call stack and stack frames
Each thread in a JVM process has its own call stack. The stack is a last-in, first-out sequence of frames. When a method is called, a new frame is pushed onto the stack. When the method returns, its frame is popped off and discarded.
A frame holds everything the currently executing method needs:
-
Local variable slots : numbered storage locations. Slot 0 in an instance method holds
this; in astaticmethod, slot 0 is the first parameter. Each parameter and each local variable declared inside the method occupies one or two slots (two forlonganddouble, which are 64 bits wide). -
Operand stack : a small working area used by bytecode instructions. When you write
a + b, the JVM loads the values ofaandbonto the operand stack, then executes aniaddinstruction that pops both, adds them, and pushes the result. - A reference to the constant pool of the current class, used to resolve symbolic names to runtime objects.
Consider this program:
public class Calculator {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = add(3, 4);
System.out.println(result);
}
}
Trace what happens when main calls add(3, 4):
-
main's frame is on the stack. The JVM evaluates the arguments, the int literals3and4. - The JVM pushes a new frame for
add. Slot 0 of theaddframe gets the value3; slot 1 gets the value4. These are copies of the argument values. - Inside
add, the bytecode instructions load slot 0 and slot 1 onto the operand stack (iload_0,iload_1), executeiaddto produce 7, and return withireturn. - The
addframe is popped. The return value 7 is placed onmain's operand stack.mainstores it in its local variable slot forresult. -
maincallsSystem.out.println(result), which triggers another frame push, executes, and returns.
Each method's frame is completely private to that invocation. The add method cannot see main's variables. main cannot see add's variables. When a frame is popped, its slots are gone.
Parameters are copies
When the JVM pushes a new frame, it copies the argument values into the new frame's local variable slots. This is the whole meaning of "Java is pass-by-value". The parameter slot always contains a copy of what was passed.
For a primitive, the copy is the number.
public static void doubleIt(int n) {
n = n * 2;
System.out.println("inside: " + n); // 10
}
public static void main(String[] args) {
int x = 5;
doubleIt(x);
System.out.println("after: " + x); // 5
}
The doubleIt frame gets a copy of 5 in slot 0. Multiplying and assigning changes only that slot. The x slot in main's frame is untouched.
This means a traditional swap function cannot work in Java:
public static void swap(int a, int b) {
int temp = a;
a = b;
b = temp;
}
// In main:
int x = 1, y = 2;
swap(x, y);
// x is still 1, y is still 2
swap exchanges the values in its own slots. Those slots contain copies. The originals in main's frame are never touched.
Parameters are copies, including reference parameters
For a reference variable, the copy is the address. The parameter slot gets a copy of the address the caller passed.
This creates the apparent contradiction that confuses newcomers: you can call a method and have it modify an object, but you can't have it reassign the caller's variable.
Here's the modification case:
public static void appendGreeting(StringBuilder sb) {
sb.append(" — have a good day");
}
public static void main(String[] args) {
StringBuilder message = new StringBuilder("Hello");
appendGreeting(message);
System.out.println(message); // Hello — have a good day
}
appendGreeting gets a copy of the address stored in message. Both message (in main's frame) and sb (in appendGreeting's frame) hold the same address. They refer to the same StringBuilder object in the heap. Calling sb.append(...) modifies the object at that address. When appendGreeting returns, message in main's frame still holds the same address, and the object at that address now has the modified content.
Here's the reassignment case:
public static void replaceMessage(StringBuilder sb) {
sb = new StringBuilder("Goodbye");
}
public static void main(String[] args) {
StringBuilder message = new StringBuilder("Hello");
replaceMessage(message);
System.out.println(message); // Hello
}
Inside replaceMessage, sb = new StringBuilder(...) stores a new address in the sb slot of the replaceMessage frame. That slot is local to this frame. It has no connection to message's slot in main's frame. When replaceMessage returns, its frame is gone, and message in main still holds the original address. "Hello" is unaffected.
The rule is consistent. Java copies the value. For a reference, the value is an address. The method can use that address to reach and modify the object, but it cannot change which object the caller's variable points to, because the method only has a copy of the address.
Stack frames in the bytecode
If you compile the Calculator example and run javap -c Calculator.class, you'll see the actual instructions. The local variable slots appear as numbered indices in instructions like iload_0 (load int from slot 0), istore_1 (store int to slot 1), aload_0 (load reference from slot 0). The a for slot 0 tells you that some instructions are reference-typed; i slots hold integers; l, f, d hold longs, floats, and doubles.
HotSpot's JIT compiler may eliminate individual frames through inlining. A small method can have its instructions merged directly into the caller, removing the frame push and pop entirely. From the JLS perspective this is invisible: inlining is a performance optimisation that doesn't change what the program does. The mental model of frames is still the right model for reasoning about scope, parameter passing, and variable lifetime.
Stack depth and StackOverflowError
The call stack has a fixed maximum depth (configurable with -Xss). Every method call pushes a frame; methods that never return keep the stack growing. Eventually the JVM runs out of stack space and throws a StackOverflowError.
The most common cause is unbounded recursion:
public static void infinite() {
infinite(); // pushes a frame, which calls infinite, which pushes a frame...
}
Each call to infinite pushes a frame before the previous one has returned. After some thousands of frames (depending on JVM settings and frame size), the stack is full.
Recursion is not inherently a problem. A correctly written recursive method has a base case that returns without recursing, limiting the depth. A depth of a few hundred is usually fine. Depths of tens of thousands may need a different approach, or explicit stack management. That's a topic for later in this series.
Prediction exercise
What does this print?
public static void modify(int[] arr) {
arr[0] = 99;
arr = new int[]{0, 0, 0};
}
public static void main(String[] args) {
int[] data = {1, 2, 3};
modify(data);
System.out.println(data[0]);
System.out.println(data.length);
}
Trace it: modify receives a copy of the address stored in data. arr[0] = 99 uses that address to modify the original array, so data[0] is affected. Then arr = new int[]{0, 0, 0} replaces the address in modify's local slot, so data in main is not affected. After modify returns, data still points to the original array, now {99, 2, 3}.
Work through the full trace, then run it to verify. If you got it right, you understand pass-by-value for reference types.

Top comments (0)