Methods and Recursion in Java
Learn how to divide a Java program into smaller reusable parts using methods. Understand parameters, return values, method overloading and recursion with simple examples.
Introduction to This Module
Imagine you are preparing a large meal. Instead of doing everything at once, you divide the work into smaller tasks: cutting vegetables, cooking rice and preparing the curry.
Methods work in a similar way in Java. They divide a large program into smaller blocks of code. Each method performs a particular task.
Recursion is another useful concept in which a method calls itself to solve a problem step by step.
What You Will Learn
- Understand what methods are and why they are used.
- Create and call methods in Java programs.
- Understand parameters and arguments.
- Return values from methods.
- Use method overloading.
- Understand recursion and its working.
- Identify the base case in recursive methods.
- Solve basic problems using recursion.
- Understand the difference between recursion and iteration.
1. Introduction to Methods in Java
What Is a Method?
A method is a block of code that performs a specific task. We write the code inside a method and execute it whenever we need that task to be performed.
For example, imagine a calculator. It can perform addition, subtraction and multiplication. Each operation can be written as a separate method.
Real-Life Example
Think of a method as a button on a washing machine. When you press the wash button, the machine performs the washing task. Similarly, when you call a method, Java executes the instructions written inside it.
Why Do We Use Methods?
- Code Reusability: Write code once and use it many times.
- Less Repetition: Avoid writing the same code repeatedly.
- Easy Maintenance: Changes can be made in one place.
- Better Organization: Large programs become easier to understand.
Simple Java Example
class Main {
static void greet() {
System.out.println("Welcome to Java!");
}
public static void main(String[] args) {
greet();
}
}
Welcome to Java!
Understanding the Code
greet()is the name of our method.- The statements inside the curly brackets form the method body.
System.out.println()displays the message.- Inside
main(), we call the method usinggreet(). - Java executes the code inside the method.
2. Creating and Calling Methods
How to Create a Method
A method generally contains a return type, method name, parentheses and a body.
returnType methodName() {
// Statements
}
Let's understand each part:
- Return Type: Tells Java what type of value the method returns. Use
voidwhen it returns nothing. - Method Name: The name used to identify and call the method.
- Parentheses: Used to write parameters, if required.
- Method Body: Contains the instructions to be executed.
Example: Creating and Calling a Method
class Main {
static void showMessage() {
System.out.println("Learning Java is easy!");
}
public static void main(String[] args) {
showMessage();
showMessage();
}
}
Learning Java is easy! Learning Java is easy!
We called showMessage() two times. Therefore,
the message was displayed two times.
static keyword allows
us to call this method directly from the static main()
method without creating an object. We will study objects in the
OOP module.
3. Method Parameters and Arguments
What Are Parameters?
Parameters are variables written inside the parentheses when we create a method. They allow us to send information to a method.
What Are Arguments?
Arguments are the actual values we provide when calling a method.
Simple Example
Suppose you ask a friend to add two numbers. Your friend needs to know which two numbers to add. These numbers are like arguments passed to a method.
Java Example
class Main {
static void add(int a, int b) {
int sum = a + b;
System.out.println("Sum = " + sum);
}
public static void main(String[] args) {
add(10, 20);
add(5, 15);
}
}
Sum = 30 Sum = 20
Understanding the Example
int aandint bare parameters.add(10, 20)passes 10 and 20 as arguments.- Java stores these values in
aandb. - The method adds the values and displays the result.
Parameters vs Arguments
| Parameters | Arguments |
|---|---|
| Written while defining a method. | Passed while calling a method. |
| Act as variables. | Are actual values or expressions. |
Example: int a |
Example: 10 |
4. Return Values and the return Statement
What Is a Return Value?
Sometimes a method should calculate something and send the
result back to the place where it was called. This is done
using the return statement.
For example, an addition method can calculate the sum and return that sum to the main method.
Example: Returning the Sum
class Main {
static int add(int a, int b) {
int sum = a + b;
return sum;
}
public static void main(String[] args) {
int result = add(10, 20);
System.out.println("Sum = " + result);
}
}
Sum = 30
How Does It Work?
- The main method calls
add(10, 20). - The values 10 and 20 are stored in
aandb. - The method calculates
10 + 20. return sumsends 30 back to the caller.- The returned value is stored in
result.
Difference Between void and int
| void Method | int Method |
|---|---|
| Does not return a value. | Returns an integer value. |
static void greet() |
static int add() |
| Used when a result does not need to be sent back. | Used when an integer result is required. |
int, it must return a compatible value on every
possible execution path.
5. Method Overloading
What Is Method Overloading?
Method overloading means creating multiple methods with the same name but different parameter lists.
The methods can have different numbers of parameters or different parameter types.
Real-Life Example
Imagine a person named Rahul who can add two numbers or three numbers. The task is still called addition, but the number of inputs is different.
Example: Overloading an add Method
class Main {
static int add(int a, int b) {
return a + b;
}
static int add(int a, int b, int c) {
return a + b + c;
}
static double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
System.out.println(add(10, 20));
System.out.println(add(10, 20, 30));
System.out.println(add(5.5, 2.5));
}
}
30 60 8.0
How Does Java Choose the Method?
- Two integer arguments call the first method.
- Three integer arguments call the second method.
- Two double arguments call the third method.
6. Introduction to Recursion
What Is Recursion?
Recursion is a programming technique in which a method calls itself to solve a problem.
Instead of solving the entire problem in one step, the method solves a smaller version of the same problem again and again.
Real-Life Example
Imagine standing between two mirrors. You may see your reflection repeated inside the mirrors. Each reflection appears inside another reflection.
Recursion is somewhat similar: a method calls itself repeatedly until a stopping condition is reached.
Simple Recursive Method
class Main {
static void countDown(int n) {
if (n == 0) {
return;
}
System.out.println(n);
countDown(n - 1);
}
public static void main(String[] args) {
countDown(5);
}
}
5 4 3 2 1
Understanding the Execution
- The main method calls
countDown(5). - The method prints 5.
- It calls itself with 4.
- It prints 4 and calls itself with 3.
- This continues until the value becomes 0.
- When
n == 0, the method returns and recursion stops.
StackOverflowError occurs.
7. How Recursion Works – Stack and Base Case
What Is a Base Case?
The base case is the condition that stops recursion. When the base case becomes true, the method stops calling itself.
What Is a Recursive Case?
The recursive case is the part where a method calls itself with a smaller or simpler input.
Understanding the Call Stack
Java uses a memory area called the call stack to keep track of method calls. When a method calls another method, Java keeps information about the current call so it can return to it later.
Think of a Stack of Plates
Imagine placing plates one above another. The last plate placed on top is the first one you remove. The call stack works in a similar way. It follows the Last In, First Out (LIFO) principle.
Example: Factorial Using Recursion
The factorial of a positive number is the multiplication of all positive integers from that number down to 1.
For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
We can also write it as:
- 5! = 5 × 4!
- 4! = 4 × 3!
- 3! = 3 × 2!
- 2! = 2 × 1!
- 1! = 1
class Main {
static int factorial(int n) {
if (n == 0 || n == 1) {
return 1;
}
return n * factorial(n - 1);
}
public static void main(String[] args) {
int result = factorial(5);
System.out.println("Factorial = " + result);
}
}
Factorial = 120
Step-by-Step Calculation
| Method Call | Calculation |
|---|---|
| factorial(5) | 5 × factorial(4) |
| factorial(4) | 4 × factorial(3) |
| factorial(3) | 3 × factorial(2) |
| factorial(2) | 2 × factorial(1) |
| factorial(1) | Returns 1 |
Now Java returns from the last call and calculates:
2 × 1 = 2
3 × 2 = 6
4 × 6 = 24
5 × 24 = 120
8. Recursion Examples – Factorial and Fibonacci
Example 1: Sum of Natural Numbers
We can use recursion to calculate the sum of numbers from 1 to n.
For example: 5 + 4 + 3 + 2 + 1 = 15.
class Main {
static int sum(int n) {
if (n == 0) {
return 0;
}
return n + sum(n - 1);
}
public static void main(String[] args) {
System.out.println(sum(5));
}
}
15
Example 2: Fibonacci Series
The Fibonacci series is a sequence in which each number is the sum of the previous two numbers.
0, 1, 1, 2, 3, 5, 8, 13, ...
The first two numbers are 0 and 1. After that, every number is calculated by adding the previous two numbers.
class Main {
static int fibonacci(int n) {
if (n == 0) {
return 0;
}
if (n == 1) {
return 1;
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
public static void main(String[] args) {
for (int i = 0; i < 7; i++) {
System.out.print(fibonacci(i) + " ");
}
}
}
0 1 1 2 3 5 8
9. Recursion vs. Iteration
What Is Iteration?
Iteration means repeating a set of instructions using loops
such as for, while and
do-while.
Recursion repeats a task by calling a method again and again. Iteration repeats a task using a loop.
Difference Between Recursion and Iteration
| Recursion | Iteration |
|---|---|
| A method calls itself. | A loop repeats statements. |
| Uses the call stack for method calls. | Usually uses less additional memory for simple loops. |
| Requires a base case. | Requires a loop condition. |
| Can be easier for naturally recursive problems. | Can be simpler and more efficient for repeated operations. |
| Too many calls can cause StackOverflowError. | Does not create a new method call for every loop repetition. |
Example: Printing 1 to 5 Using a Loop
class Main {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
1 2 3 4 5
Example: Printing 1 to 5 Using Recursion
class Main {
static void printNumbers(int n) {
if (n > 5) {
return;
}
System.out.println(n);
printNumbers(n + 1);
}
public static void main(String[] args) {
printNumbers(1);
}
}
1 2 3 4 5
Important Java Interview Questions
Q1. What is a method in Java?
A method is a block of code that performs a specific task. It helps make programs reusable and organized.
Q2. What is the difference between parameters and arguments?
Parameters are variables declared in a method definition. Arguments are the actual values passed when calling the method.
Q3. What is the purpose of the return statement?
The return statement sends a value back from a method to the place where the method was called. It also ends the current method execution.
Q4. What is method overloading?
Method overloading allows multiple methods to have the same name but different parameter lists.
Q5. Can we overload a method by changing only its return type?
No. The parameter list must be different. Changing only the return type is not sufficient.
Q6. What is recursion?
Recursion is a technique in which a method calls itself to solve a problem.
Q7. What is a base case?
A base case is the stopping condition that prevents a recursive method from calling itself forever.
Q8. What happens if recursion has no base case?
The method may continue calling itself until the call stack runs out of space, causing a StackOverflowError.
Q9. What is the difference between recursion and iteration?
Recursion repeats a task through method calls, while iteration repeats a task using loops.
Q10. What is the call stack?
The call stack is the memory structure Java uses to manage active method calls and their execution.
Module Summary
- A method is a reusable block of code.
- Methods are created using a return type and a method name.
- Parameters receive values and arguments provide those values.
- The return statement sends a result back to the caller.
- Method overloading uses the same method name with different parameter lists.
- Recursion happens when a method calls itself.
- A base case is necessary to stop recursion.
- The call stack manages active method calls.
- Recursion and iteration are two ways to repeat a task.
Practice Questions
Try solving these questions yourself before moving to the next module.
- Write a method to print "Hello Java".
- Write a method that accepts two numbers and prints their sum.
- Write a method that returns the square of a number.
- Create overloaded methods to calculate the area of a square and rectangle.
- Write a recursive method to calculate the factorial of a number.
- Write a recursive method to find the sum of natural numbers.
- Write a recursive method to print numbers from 1 to 10.
- Write a program to generate the Fibonacci series.
- Explain the difference between recursion and iteration with examples.
- What happens when a recursive method does not have a base case?
Congratulations! Module 04 Completed
You have learned how to create reusable methods, pass information to methods, return values and solve problems using recursion. These concepts are important for writing clean Java programs and solving placement coding questions.
Practice the questions before moving to the next module.