Topic 5 of 30 · Beginner
Methods & Recursion
Parameters, return values, overloading and recursion.
Concept
A method groups reusable logic. It has a return type, a name and parameters. Static methods belong to the class; instance methods need an object.
Overloading = same name, different parameter lists. The return type alone can't distinguish overloads.
A recursive method calls itself with a smaller problem and needs a base case; too much depth causes StackOverflowError.
Code (Java 21)
static int add(int a, int b) { return a + b; }
static double add(double a, double b) { return a + b; } // overload
static long factorial(int n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
static int sum(int... nums) { // varargs
int s = 0;
for (int n : nums) s += n;
return s;
}Remember
- Overload by parameters, not return type.
- Every recursion needs a base case.
- Varargs must be the last parameter.
Interview questions
Can we overload main?
Yes, but the JVM only calls public static void main(String[] args).
What causes StackOverflowError?
Recursion too deep (often a missing base case), filling the thread's call stack.
Lesson test
Take an 8-question test on “Methods & Recursion” — concepts, output prediction, bug spotting and interview questions.