Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tail Recursion in java

Tags:

java

Is this a good example to show tail recursion?

public printName(){
    System.out.println("Smith");
    printName();
}

I'm not intending to do this in real life, but i put this as an example for my exam. Is this one correct?

like image 310
user1419170 Avatar asked Nov 28 '22 03:11

user1419170


2 Answers

No, for two reasons:

  • tail recursion is only valuable when compiler supports it (tail call optimization). In Java it will still end with StackOverflowError

  • it would be nice to show some stop condition. Your code is equivalent to loop running forever.

Consider almost identical code in Scala, the only difference is that Scala compiler will perform tail call optimization and the loop runs forever:

def printName() {
  println("Smith"); 
  printName()
}
like image 199
Tomasz Nurkiewicz Avatar answered Nov 29 '22 15:11

Tomasz Nurkiewicz


A better example of tail recursion would be something like this:

public printName(int level){
    if( level <= 0 )
         return;
    System.out.prntln("Smith");
    printName(--level);
}

This examples includes the important part where the recursion is terminated.

Besides of this: As other answers already noted: Since Java does not optimize tail-recursion, there is no point in using it in this language. So you basically end up to optimize your algorithm yourself - by making it iterative. That's the point of tail-recursion: It can be proved, that any tail-recursive algorithm can be transformed into an iterative algorithm.

like image 23
A.H. Avatar answered Nov 29 '22 16:11

A.H.