Reverse All Characters of a String in Java

In this Java tutorial, we will learn to reverse the characters of a string using the recursion and StringBuilder.reverse() methods. You may like to read about reversing the words in a sentence also.

1. Reverse using Recursion

To reverse all the characters of the string, we can write a recursive function that will perform the following actions –

  • Take the first character and append it to the last of the string
  • Perform the above operation, recursively, until the string ends
public class ReverseString {

  public static void main(String[] args) {

    String blogName = "How To Do In Java";
    String reverseString = reverseString(blogName);

    Assertions.assertEquals("avaJ nI oD oT woH", reverseString);
  }

  public static String reverseString(String string) {
    if (string.isEmpty()) {
      return string;
    }
    return reverseString(string.substring(1)) + string.charAt(0);
  }
}

2. Reverse using StringBuilder.reverse()

We can also reverse a string easily, using a StringBuilder.reverse() method. The reverse() method causes the characters of String to be replaced by the reverse of the sequence.

String blogName = "How To Do In Java";

String reverseString = new StringBuilder(blogName).reverse().toString();

Assertions.assertEquals("avaJ nI oD oT woH", reverseString);

Happy Learning !!

Sourcecode on Github

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode