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?
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()
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With