Menu

Recursive method in Java

How to write a recursive method in Java?

Below is the code snippet of a recursive method in Java to generate numbers and check the number and execute the method again. In the below example printNumber() is a recursive method that will get called inside its own body.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package rashidjorvee;

public class RecursiveMethod {

 public static void main(String[] args) {

  RecursiveMethod recursiveMethod=new RecursiveMethod();
  recursiveMethod.printNumber(2);

 }
 private void printNumber(int j) {
  try {
   int i=j; 
    if(i==2) {
     printNumber(4);
    }
    System.out.println("Number "+i);
    }
  catch(Exception e) {

  }
 }
}

No comments:

Post a Comment