Write a program to reverse a string using recursion in Java

Carvia Tech | May 18, 2019 | 1 min read | 19 views | Java Coding Challenges

In this article, we will write a program to reverse a string entered by a user.


  1. We will remove first character from the input string and append it at the end.

  2. 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 can write a simple Junit based testcase to assert the correctness of our given program.

JUnit testcase

import org.junit.Test;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.*;

public class ReverseStringTest {

    public void reverse() {
        ReverseString utils = new ReverseString();
        assertThat(utils.reverse("carvia"), equalTo("aivrac"));

Java Coding Challenges:
  1. How will you check if a given sentence is a pangram
  2. Calculate factorial of a number in Java using recursion
  3. Check a number is Prime: Java Coding Problem
  4. Create anagram buckets from a given input array of words
  5. Find two numbers of which the product is maximum in an array
  6. Java program to check if two strings are anagrams
  7. How to check if the given number is palindrome in Java
See all articles in Java Coding Challenges
Top articles in this category:
  1. Top 50 SDET Java Programming Interview Questions & Answers
  2. Write a program to reverse the order of words in a string
  3. Java program to check if two strings are anagrams
  4. How to reverse a number in Java
  5. Commonly used Http methods in RESTful services
  6. Find longest non-repeating substring from a given string in Java
  7. Calculate factorial of a number in Java using recursion

Find more on this topic:
SDET Interviews image
SDET Interviews

End to end automation testing using Selenium Web Driver, Rest Assured, JMeter, Junit, TestNG etc.

Last updated 1 month ago

Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info