Java Methods and Recursion
Method Fundamentals
Methods in Java serve as fundamental building blocks for organizing code. They enable modular programming, code reuse, and improved readability. When code complexity increases, methods help break down problems into manageable units.
Method Definition
A method in Java follows this structure:
modifier returnType methodName(parameterType param1, parameterType param2) {
// method body
return value;
}
Method Components
- Modifiers: Control access and behavior (public, static, private, etc.)
- Return Type: Data type of the value returned (or void if none)
- Method Name: Descriptive identifier folowing camelCase convention
- Parameter List: Input values the method accepts
- Method Body: Contains the executable code
Method Invocation Process
When a method is called:
- Arguments are passed to parameters
- Control transfers to the method
- Method executes its code
- Return value is sent back (if applicable)
- Control returns to the caller
Parameter Passing
Java uses pass-by-value for all parameters:
public static void modifyValue(int value) {
value = 100; // Only affects local copy
}
public static void main(String[] args) {
int num = 50;
modifyValue(num);
// num remains 50
}
Method Overloading
Methods can share the same name with diffreent parameter lists:
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
public int add(int a, int b, int c) {
return a + b + c;
}
}
Method Signatures
The method signature includes the method name and parameter types, which the compiler uses for resolution:
public int calculate(int x, String y) { ... }
// Signature: calculate(int, String)
Recursion in Java
Recursion occurs when a method calls itself to solve a problem by breaking it into smaller instances.
Essential Recursion Conditions
- Base case: The condition that stops recursion
- Recursive step: The method calls itself with modified parameters
Factorial Calculation Example
public static int factorial(int n) {
if (n <= 1) {
return 1; // Base case
}
return n * factorial(n - 1); // Recursive step
}
Understanding the Call Stack
Each recursive call creates a new stack frame containing:
- Local variables
- Parameters
- Return address
Recursive Practice Exercises
Exercise 1: Digit Extraction
Print each digit of a number in order:
public static void printDigits(int number) {
if (number >= 10) {
printDigits(number / 10);
}
System.out.println(number % 10);
}
Exercise 2: Sum of First N Numbers
Calculate the sum of numbers from 1 to N:
public static int sumToN(int n) {
if (n == 1) {
return 1;
}
return n + sumToN(n - 1);
}
Exercise 3: Digit Sum
Calculate the sum of all digits in a number:
public static int digitSum(int number) {
if (number < 10) {
return number;
}
return (number % 10) + digitSum(number / 10);
}
Exercise 4: Fibonacci Sequence
Compute the Nth Fibonacci number (with optimization):
public static int fibonacci(int n) {
if (n <= 2) {
return 1;
}
int prev = 1;
int curr = 1;
int next = 0;
for (int i = 3; i <= n; i++) {
next = prev + curr;
prev = curr;
curr = next;
}
return curr;
}
Important Considerations
- Recursion can lead to stack overflow for deep calls
- Some problems are better solved iteratively
- Always ensure a base case exists
- Recursive solutions may be less efficient than iterative ones