Foundation

06 — Methods

Previous: 05 Loops · Next: 07 Arrays

▶️ java pkg1core/core7Methods.java


What is a method?

A method is a named block of code that performs one task. It avoids duplication and organizes logic.

java
1static int add(int a, int b) {2    return a + b;3}4 5public static void main(String[] args) {6    System.out.println(add(3, 4));   // 77}
Part Meaning
static Belongs to class, not an object
int Return type (void = nothing)
add Method name
(int a, int b) Parameters
return Sends value back to caller

Pass-by-value

Java is always pass-by-value.

  • Primitives: the value is copied.
  • Objects: the reference is copied (you can mutate the object, but reassigning the parameter doesn't affect the caller).
java
1static void tryReassign(int[] arr) {2    arr[0] = 99;              // mutates caller's array ✓3    arr = new int[]{0};       // reassigns local copy only ✗4}

Method overloading

Same name, different parameter lists — resolved at compile time.

java
1static int add(int a, int b) { return a + b; }2static double add(double a, double b) { return a + b; }

Not overloading: different return type only (compiler can't distinguish).


Varargs

java
1static int sum(int... values) {2    int total = 0;3    for (int v : values) total += v;4    return total;5}6// sum(1, 2, 3, 4) → 10

int... is treated as int[] inside the method.


Recursion

A method that calls itself. Needs a base case to stop.

java
1static long factorial(int n) {2    if (n <= 1) return 1;           // base case3    return n * factorial(n - 1);    // recursive step4}

⚠️ Deep recursion → StackOverflowError. Iteration or tail-recursion awareness for large inputs.


Practice

  1. Run core7Methods.
  2. Write an overloaded max for int and double.
  3. Write recursive fibonacci(n) and trace fib(5) on paper.

Next → 07 Arrays Related → 01 Core Java