Reverse a String Using Recursion in Java
Recursion in Java is a process in which a method calls itself continuously. In the programming language, if a program allows us to call a function inside the same function name, it is known as a recursive call of the function. It makes the code compact but it is difficult to understand. It is used to solve the complex problem that can be broken into smaller repetitive problems. Using recursion, we can solve many complex problems like the factorial program, Fibonacci series, etc. Similarly, we can also use recursion to reverse a String in Java. In this section, we will learn how to reverse a string using recursion in Java.
The recursive function performs the following steps to reverse a string:
Suppose, the input string JAVATPOINT is to be reversed. We will remove the first character from the string and append it to a variable reversesting. Let's implement the functionality in a Java program and reverse the string using recursion.
In the following example, we have created a method named reverseString(). It parses the string that we want to reverse. Inside the method, first, we have checked that the string is empty or not. If the string is empty, it returns the same string and also prints String is empty. We have used the following two methods of the String class:
substring(): It returns the new string that is a substring of the specified string. It parses a parameter that specifies the starting index (beginning) of the substring.
charAt(): It returns a character at the specified index. The index lies between 0 too length()-1.
Let's see another example to reverse a string using recursion.
In the following example, we have created a method named reverseString(). It parses the string that we want to reverse. Inside the method, we have tested two conditions using the logical OR operator. First, we have compared the string with null and in the second condition, we have found the length of the string and compared it with 1. If either or both the conditions return true, the method prints the same string.
In the else part, we have called the reverseString() method recursively that reverse the string. The method parses a substring returned by the substring() method. The substring() method also parses the two parameters the begin index and the end index. It returns the substring of the specified string. Therefore, it reverses the string recursively.