🎯 Java Methods — Parameters, Overloading, Varargs and Recursion
Master Java methods — declaration, parameters, return types, method overloading, varargs, pass-by-value semantics, static vs instance methods and recursion with examples.
A method is a named, reusable block of code that optionally takes parameters and returns a value.
📜 Anatomy
public int add(int a, int b) {
return a + b;
}Signature = name + parameter types (return type is NOT part of the signature).
🎭 Overloading
Same name, different parameter lists. The compiler picks the match at compile time:
int max(int a, int b) { ... }
double max(double a, double b) { ... }📚 Varargs
int sum(int... nums) { // 0..N ints
int total = 0;
for (int n : nums) total += n;
return total;
}
sum(1, 2, 3); // 6📦 Java is ALWAYS pass-by-value
Critical interview point: Java copies the value of every argument. For objects, the value copied is the reference — so you can mutate the object's fields, but reassigning the parameter doesn't affect the caller. There is no pass-by-reference in Java.
🌀 Recursion
A method calling itself with a smaller input, plus a base case. Elegant for trees and divide-and-conquer; watch for StackOverflowError on deep recursion.
💻 Code Examples
Pass-by-value with objects
static void rename(StringBuilder sb) {
sb.append(" Smith"); // mutates the object — visible
sb = new StringBuilder("X"); // reassigns local copy — NOT visible
}
StringBuilder name = new StringBuilder("Sam");
rename(name);
System.out.println(name);Sam Smith
Overloading resolves by argument type
static void print(int x) { System.out.println("int: " + x); }
static void print(double x) { System.out.println("double: " + x); }
print(5);
print(5.0);int: 5 double: 5.0
Recursion: factorial
static long fact(int n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
System.out.println(fact(5));120
⚠️ Common Mistakes
- Thinking Java is pass-by-reference for objects — it's pass-by-value of the reference; reassigning the parameter doesn't affect the caller.
- Trying to overload by return type alone — not allowed; the signature ignores return type.
- Putting varargs anywhere but last in the parameter list — it must be the final parameter.
- Deep recursion without a base case or with too many frames — StackOverflowError.
🎯 Interview Questions
Real questions asked at top product and service-based companies.
Q1.Is Java pass-by-value or pass-by-reference?Intermediate
Q2.What is method overloading?Beginner
Q3.Can you overload methods by return type only?Intermediate
Q4.What are varargs?Beginner
Q5.What's the difference between overloading and overriding?Advanced
🧠 Quick Summary
- Signature = name + parameter types (not return type).
- Overloading = same name, different parameters, compile-time resolution.
- Varargs (int...) must be the last parameter.
- Java is ALWAYS pass-by-value (of the reference for objects).
- Recursion needs a base case; beware StackOverflowError.