Core Java Fundamentals · Methods

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.

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.