Signup/Sign In

How to reverse String in Java

In this post, we are going to reverse a string. The String is a sequence of characters and a class in Java that is used to handle string data.

To reverse a string, we either can use the reverse() method of StringBuilder class or a convenient way to arrange the characters into a new string in reverse order. We will use both the ways with the help of examples.

The StringBuilder is similar to String class except that it is mutable. So, it's content can be changed.

The reverse() method does not take any parameter and used to reverse the character sequence. It returns StringBuilder rather than String. So, if you want string back then use the toString() method to get a String object.

Time for an Example:

Let's create an example to get the reverse of a string. Here, we are using StringBuilder and passes string argument to the StringBuilder's constructor. After that by using the reverse() method of StringBuilder class, we get a reverse string.

public class Main {
	public static void main(String[] args){
		String str = "Studytonight";
		System.out.println(str);
		StringBuilder strb = new StringBuilder(str);
		strb.reverse();
		System.out.println(strb);
	}
}


Studytonight
thginotydutS

Example:

Let's take another example to reverse a string. Here, we are using charAt() method to fetch individual character of the string and append into a new string object to get a new string.

public class Main {
	public static void main(String[] args){
		String str = "Studytonight";
		System.out.println(str);
		String str2 = "";
		for (int i = str.length()-1; i>=0; i--) {
			str2 += str.charAt(i);
		}
		System.out.println(str2);
	}
}


Studytonight
thginotydutS



About the author:
I am a 3rd-year Computer Science Engineering student at Vellore Institute of Technology. I like to play around with new technologies and love to code.