java recursion within class 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) );
}
}
Example 2: 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));
}