Core Java Fundamentals · Methods
Package code into methods, pass values in, and get a result back. Watch each call get its own frame on the stack.
public class MethodsDemo {
static int square(int n) {
int result = n * n;
return result;
}
static void greet(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
int a = square(4);
int b = square(a - 13);
greet("Asha");
System.out.println(a + b);
}
}result is a local variable of this call: 4 × 4 = 16.return sends 16 back to the caller, and this frame is removed.a gets the returned value, 16.result is created on the stack with the value 9.square() has finished, so its variables are gone.b.Hello, Asha.greet() has finished, so its variables are gone.25.