Reversing a String in Java

In this Java tutorial, we will learn to reverse a string using the recursion and StringBuilder.reverse() method.

Read More: Reversing the Words in a String

1. Reverse a String using Recursion

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

  1. Take first character and append to last of string
  2. Perform above operation, recursively, until the string ends
public class StringExample
{
	public static void main(String[] args)
	{
		String blogName = "How To Do In Java ";

		String reverseString = reverseString(blogName);

		System.out.println(reverseString);
	}

	public static String reverseString(String string)
	{
		if (string.isEmpty()){
		     return string;
		}

		//Calling function recursively
		return reverseString(string.substring(1)) + string.charAt(0);
	}
}

Program output.

avaJ nI oD oT woH

2. Reverse A String using StringBuilder

We can also reverse a string easily, using a StringBuilder.reverse() method.

String blogName = "How To Do In Java";

String reverseString = new StringBuilder(string).reverse();

System.out.println(reverseString);  

Program output.

avaJ nI oD oT woH

Happy Learning !!

Leave a Reply

2 Comments
Most Voted
Newest Oldest
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