Iteration Vs Recursion

Q1. Can you write a sample code that will count the number of “A”s in a given text “AAA rating“? Show both iterative and recursive approaches?


A for loop to traverse through each character of the String “AAA rating”, and a if condition to check for “A” & increment “count” by 1 if the character is “A”.




It can be a bit tricky to visualise recursion. A powerful technique, especially when you want to work with a Tree data structure that has a parent child relationship.



What is a re-entrant method?

A re-entrant method would be one that can be safely entered, even when the same method is being executed, further down the call stack of the same thread. A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it can be tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms. All recursive functions are re-entrant, but not all re-entrant functions are recursive.

Stack data structure uses LIFO (Last In First Out), so it remembers its ‘caller’ and knows whom to return when the function has to return. Recursion makes use of system stack for storing the return addresses of the function calls. Java is a stack based language.

What is a stop or exit condition?

Recursive calls must have a stop or exit condition with a “return” statement. If not you will get a StackOverflowException. You need a condition to stop recursion as it cannot go on for ever.

What is a tail recursion?

Learn more at Recursion Vs Tail Recursion.

300+ Java & Big Data Interview FAQs

16+ Java Key Areas Interview Q&As

800+ Java Interview Q&As

300+ Java & Big Data Tutorials