carvia
Reverse a string using recursion in Java
Upasana | November 21, 2020 | 1 min read | 105 views | Java Coding Challenges
In this article, we will write a program to reverse character positions in a given string using recursive approach.
Sample input
Reversed output
aivrca
Recursive Approach
-
We will remove first character from the input string and append it at the end.
-
Repeat it till all the characters are removed and input becomes empty.
Java source
Reverse a string using Recusion Java
public class ReverseString {
public String reverse(String input) {
if (input.isEmpty()) { (1)
System.out.println("String is empty now");
return input;
}
return reverse(input.substring(1)) + input.charAt(0); (2)
}
}
1 | Base condition in recursion |
2 | Tail recursion |
JUnit testcase
We will write a simple Junit based testcase to assert the correctness of our given program.
JUnit Test
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;
public class ReverseStringTest {
@Test
public void reverse() {
ReverseString utils = new ReverseString();
assertThat(utils.reverse("carvia"), equalTo("aivrac"));
}
}
That’s all.
Java Coding Challenges:
- Reverse position of words in a string using recursion
- Check if the given string is palindrome
- Find two numbers of which the product is maximum in an array
- Prime number checker in Java
- Create anagram buckets from a given input array of words
- Anagrams string checker in Java
- Java Program to find Factorial of a number
Top articles in this category:
- Reverse position of words in a string using recursion
- Reverse order of words inside string in Java
- Java Coding Problems for SDET Automation Engineer
- How to reverse a number in Java
- 50 Java Interview Questions for SDET Automation Engineer
- Java Program to find Factorial of a number
- Find longest non-repeating substring from a given string in Java
Recommended books for interview preparation:
Book you may be interested in..
Book you may be interested in..