Methods: Define, Call and Return

Package code into methods, pass values in, and get a result back. Watch each call get its own frame on the stack.

Java · beginner · 8 min · 13 steps · free

What you'll learn

MethodsDemo.java

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);
    }
}

Step by step

  1. main calls square(4). Java pauses main and starts a new frame for square, with n = 4.
  2. result is a local variable of this call: 4 × 4 = 16.
  3. return sends 16 back to the caller, and this frame is removed.
  4. a gets the returned value, 16.
  5. square(a - 13): the argument is worked out first, 16 - 13 = 3, then passed in.
  6. result is created on the stack with the value 9.
  7. square() has finished, so its variables are gone.
  8. The value it returned, 9, is stored in b.
  9. greet is a void method: it does a job (printing) but returns nothing.
  10. It prints Hello, Asha.
  11. greet() has finished, so its variables are gone.
  12. It prints 25.
  13. a = 16 and b = 9, so it prints 25. Methods take parameters, may return a value, and each call has a separate frame.

Common mistakes

Best practices

Key takeaways

Check yourself

static int twice(int x) { return x * 2; } — what is twice(twice(3))?

Answer: 12. twice(3) = 6, then twice(6) = 12.

What happens to a method's local variables after it returns?

Answer: They disappear with its frame. Each call gets fresh local variables.

·

More in Methods