Tutorial 3
Methods, Static Methods and Recursion in Java
1. Introduction
● A method is a block of code that performs a specific task.
● Methods help in code reusability, modularity, and easy maintenance.
● Java supports instance methods, static methods, and recursive methods.
2. Methods in Java
2.1 What is a Method?
● A method is a function defined inside a class.
● It is used to perform an operation or return a result.
● A method is called using an object of the class.
2.2 Simple Method Example
class Demo {
void show() {
[Link]("This is a method");
}
public static void main(String[] args) {
Demo d = new Demo();
[Link]();
}
}
Explanation:
● show() is a method.
● It is called using the object d.
2.3 Method with Parameters
class Demo {
void add(int a, int b) {
[Link]("Sum = " + (a + b));
}
public static void main(String[] args) {
Demo d = new Demo();
[Link](10, 20);
}
}
3. Static Methods
3.1 What is a Static Method?
● A static method belongs to the class, not to the object.
● It can be called without creating an object.
● Static methods are declared using the static keyword.
3.2 Simple Static Method Example
class StaticDemo {
static void display() {
[Link]("This is a static method");
}
public static void main(String[] args) {
[Link]();
}
}
Explanation:
● display() is a static method.
● It is called using the class name.
3.3 Static Method with Parameters
class StaticDemo {
static int square(int x) {
return x * x;
}
public static void main(String[] args) {
[Link]("Square = " + square(5));
}
}
4. Recursion
4.1 What is Recursion?
● Recursion is a technique where a method calls itself.
● Every recursive method must have:
o Base condition (to stop recursion)
o Recursive call
4.2 Simple Recursive Example (Factorial)
class RecursionDemo {
static int factorial(int n) {
if (n == 0)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String[] args) {
[Link]("Factorial = " + factorial(5));
}
}
Explanation:
● factorial() calls itself.
● n == 0 is the base condition.
4.3 Simple Recursive Example (Sum of Numbers)
class RecursionDemo {
static int sum(int n) {
if (n == 0)
return 0;
else
return n + sum(n - 1);
}
public static void main(String[] args) {
[Link]("Sum = " + sum(5));
}
}
5. Comparison: Method vs Static Method
Feature Method Static Method
Belongs to Object Class
Object needed Yes No
Accessed using Object Class name
Uses instance variables Yes No
6. Problem Statements (Concept Check)
1. Write a method to find the maximum of two numbers.
2. Write a static method to calculate area of a circle.
3. Write a method to print all even numbers between 1 and 50.
4. Write a recursive method to find factorial of a number.
5. Write a recursive method to find sum of digits of a number.