recursion in Java code example

Example 1: recursion in java

class scratch{
    public static long factorial(int n){
        if ( n == 1 ){
            return 1;
        }
        else{
            return n * factorial( n - 1 );
        }
    }
    public static void main(String[] args) {
        System.out.println( factorial(5) );
        //Print 120 (5!) to the console
    }
}

Example 2: java recursion

// prints x number of $
public static void recursion(int x) {
  if(x == 0) { // base case
    System.out.println();
  } else { // recursive case
    System.out.print("$");
    recursion(x - 1);
  }
}

Example 3: recursion in java

Recursion is a basic programming technique
you can use in Java, in which a method
calls itself to solve some problem. 
  A method that uses this technique
  is recursive. Many programming problems
  can be solved only by recursion,
and some problems that can be solved by
other techniques are better solved by recursion.

EXP-1: Factorial
	
	public static long factorial(int n){
        if (n == 1)
            return 1;
        else
            return n * factorial(n-1);
    }

EXP-2: Fibonacci
	
	static int n1=1, n2=2, n3=0;
    public static void printFibo(int count){
        if (count > 0) {
            n3 = n1 + n2;
            n1 = n2;
            n2 = n3;
            System.out.print(" " + n3);
            printFibo(count-1);
        }
    }

Example 4: java recursion

public void removeDigits(String string) {
  if(string.length == 1) {
    if(Character.isDigit(string.CharAt(0))) {
      return "";
    } else {
      return string;
    }
  } else {
    if(Character.isDigit(string.CharAt(0))) {
      return removeDigits(string.substring(1));
    } else {
      return string.substring(0, 1) + removeDigits(string.substring(1));

public static void main(String[] args) {
  String string = "1a2b3c"
  System.out.println(removeDigits(string)); //will print "abc"
}

Tags:

Java Example