Recursion in Java
Recursion in java is a process in which a method calls itself
continuously. A method in java that calls itself is called recursive method.
Fig: Recursion in java |
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}
Example 1: Infinite times
public class RecursionExample1 {
static void p(){
System.out.println("hello");
p();
}
public static void main(String[] args) {
p();
}
}
Output:
hello
hello
...
java.lang.StackOverflowError
Example 2: Finite times
public class RecursionExample2 {
static int count=0;
static void p(){
count++;
if(count<=5){
System.out.println("hello "+count);
p();
}
}
public static void main(String[] args) {
p();
}
}
Output:
hello 1
hello 2
hello 3
hello 4
hello 5
No comments:
Post a Comment