Recursive method in Java
Recursive method in Java – A method call by itself is called as Recursive method.
Method Parameters
Method parameters are the values that you pass to a method when you call it. These parameters are used by the method to perform operations.
Example:
public class Example {
public static void greet(String name) {
System.out.println("Hello, " + name);
}
public static void main(String[] args) {
greet("Alice"); // Passing "Alice" as a parameter
}
}
Explanation
greet(String name)
is a method with a parametername
of typeString
.- When
greet("Alice")
is called, “Alice” is passed to thename
parameter, and the method prints “Hello, Alice”.
Method Overloading in Java
Method overloading allows a class to have more than one method with the same name, but with different parameters (different type, number, or both).
Example:
public class Example {
public static void print(int num) {
System.out.println("Number: " + num);
}
public static void print(String str) {
System.out.println("String: " + str);
}
public static void main(String[] args) {
print(10); // Calls print(int num)
print("Hello"); // Calls print(String str)
}
}
Explanation:
- There are two methods named
print
, one that takes anint
parameter and another that takes aString
parameter. - Depending on the argument type, the appropriate method is called.
Method Scope
Method scope refers to the visibility and lifetime of variables defined within a method. Variables declared within a method are local to that method and cannot be accessed outside of it.
Example:
public class Example {
public static void display() {
int number = 10; // Local variable
System.out.println("Number: " + number);
}
public static void main(String[] args) {
display();
// System.out.println(number); // This would cause a compile-time error
}
}
Explanation:
- The variable
number
is declared within thedisplay
method and is local to that method. - Attempting to access
number
outside of thedisplay
method (e.g., inmain
) will result in a compile-time error.
Recursive Method in Java
A recursive method is a method that calls itself in order to solve a problem. Each recursive call should progress towards a base case that stops the recursion.
Example:
public class Example {
public static int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive call
}
}
public static void main(String[] args) {
int result = factorial(5); // 5! = 5 * 4 * 3 * 2 * 1 = 120
System.out.println("Factorial of 5: " + result);
}
}
Explanation:
- The
factorial
method calculates the factorial of a given numbern
recursively. - If
n
is 0, the base case returns 1. - Otherwise, it returns
n * factorial(n - 1)
, which is a recursive call to calculate the factorial ofn - 1
.
These concepts form the foundation of method usage in Java. Understanding them is crucial for writing efficient and maintainable code.