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.
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).
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.
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
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) → 10int... is treated as int[] inside the method.
Recursion
A method that calls itself. Needs a base case to stop.
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
- Run
core7Methods. - Write an overloaded
maxforintanddouble. - Write recursive
fibonacci(n)and tracefib(5)on paper.
Next → 07 Arrays Related → 01 Core Java
Source named in this chapter
- core7Methodspkg1core/core7Methods.java