User John Selawsky
John Selawsky
Senior Java Developer and Tutor at LearningTree

Reverse a String in Java

Published in the Java Developer group

What is a Reverse String?

“Start reading a String beginning from its last character all the way up to the first character. Bingo! that was your reversed string."
Here’s a demonstration of how it will look like.

Input String = "X Y Z";
Output String = "Z Y X"

Input String = "1 2 3";
Output String = "3 2 1";

Input String = "I love Java!";
Output String = "!avaJ evol I";

How to Reverse a String in Java?

There are different ways to reverse a String in Java. However, Java does not provide any reverse() method for String class. The naive approach begins with using for loop. The traditional iterative procedure. Later we can build it up by using reverse() methods offered by other classes like StringBuilder and StringBuffer.

Method 1 - The Old School Iterative Way


public class StringReversal {

	public static String reverseInputString(String myString) {

		if (myString == null)
			return myString;

		String reverseString = "";

		for (int i = myString.length() - 1; i >= 0; i--) {		

			reverseString = reverseString + myString.charAt(i);
		}
		return reverseString;
	}

	public static void main(String[] args) {

		String myString1 = "X Y Z";
		System.out.println("reverse(" + myString1 + ") = " + reverseInputString(myString1));

		String myString2 = "1 2 3";
		System.out.println("reverse(" + myString2 + ") = " + reverseInputString(myString2));

		String myString3 = "I LOVE JAVA!";
		System.out.println("reverse(" + myString3 + ") = " + reverseInputString(myString3));

		String myString4 = "My favourite place to learn Java is CodeGym.";
		System.out.println("reverse(" + myString4 + ") = " + reverseInputString(myString4));

		String myString5 = "My name is Lubaina Khan.";
		System.out.println("reverse(" + myString5 + ") = " + reverseInputString(myString5));
		
		// Boundary Case to see what happens if a String is null
		String myString6 = null;
		System.out.println("reverse(" + myString6 + ") = " + reverseInputString(myString6));
		
		// Boundary Case to see what happens if a String is empty
		String myString7 = "";
		System.out.println("reverse(" + myString7 + ") = " + reverseInputString(myString7));
	}
}

Output

reverse(X Y Z) = Z Y X reverse(1 2 3) = 3 2 1 reverse(I LOVE JAVA!) = !AVAJ EVOL I reverse(My favourite place to learn Java is CodeGym.) = .myGedoC si avaJ nrael ot ecalp etiruovaf yM reverse(My name is Lubaina Khan.) = .nahK aniabuL si eman yM reverse(null) = null reverse() =

Explanation


public static String reverseInputString(String myString) { ... }
The method reverseInputString takes an Input String called myString.

if (myString == null)
	return myString;
Check if the input String i-e myString is null. If found null, return the input as it is. We don’t need to proceed further. This is called boundary case handling to avoid any errors.

String reverseString = "";
Declare an empty String to store the output.

for (int i = myString.length() - 1; i >= 0; i--) {		
	reverseString = reverseString + myString.charAt(i);
}
Use a normal for loop. Initialize the iterator i from the last index of the input String. Access the last index of the input string and store it in the output string. Keep repeating till you reach the 0th index or the beginning of the input string.

return reverseString;
Return the reverseString and use it as per your requirements.

Method 2 - The Use of String Builder Class

In Java, the contents of a String once initialized can not be changed. Hence, there is no reverse() method available for Strings. But other classes like StringBuilder and StringBuffer in Java do contain contents that are mutable or changeable. To reverse a string without loops, and using the built-in StringBuilder or StringBuffer class let’s look at an example below.

public class StringBuilderReversal {

	public static void main(String[] args) {

		String input1 = "A B C";
		StringBuilder inputText1 = new StringBuilder(input1);
		System.out.println("reverse(" + inputText1 + ") = " + inputText1.reverse());

		String input2 = "0 1 2 2 3 3 3";
		StringBuilder inputText2 = new StringBuilder(input2);
		System.out.println("reverse(" + inputText2 + ") = " + inputText2.reverse());

		String input3 = "Monday";
		StringBuilder inputText3 = new StringBuilder(input3);
		System.out.println("reverse(" + inputText3 + ") = " + inputText3.reverse());

		String input4 = "I love CodeGym!";
		StringBuilder inputText4 = new StringBuilder(input4);
		System.out.println("reverse(" + inputText4 + ") = " + inputText4.reverse());

		 // ReverseString using the StringBuilder class
		StringBuilder inputText5 = new StringBuilder("Reverse this String using StringBuilder Class.");
		System.out.println("reverse(" + inputText5 + ") = " + inputText5.reverse());

		 // ReverseString using the StringBuffer class
		StringBuffer inputText6 = new StringBuffer("Reverse this String using StringBuffer Class.");
		System.out.println("reverse(" + inputText6 + ") = " + inputText6.reverse());
	}
}

Output

reverse(A B C) = C B A reverse(0 1 2 2 3 3 3) = 3 3 3 2 2 1 0 reverse(Monday) = yadnoM reverse(I love CodeGym!) = !myGedoC evol I reverse(Reverse this String using StringBuilder Class.) = .ssalC redliuBgnirtS gnisu gnirtS siht esreveR reverse(Reverse this String using StringBuffer Class.) = .ssalC reffuBgnirtS gnisu gnirtS siht esreveR

Explanation


String input1 = "A B C";
StringBuilder inputText1 = new StringBuilder(input1);
To reverse the input String you need to convert it to the StringBuilder. For that, pass the input String to the StringBuilder constructor.

System.out.println("reverse(" + inputText1 + ") = " + inputText1.reverse());
After converting String to the StringBuilder, you can get its reverse and print the output.

 // ReverseString using the StringBuffer class
StringBuffer inputText6 = new StringBuffer("Reverse this String using StringBuffer Class.");
Alternatively, you can pass a String directly to the StringBuilder or StringBuffer. Reverse a String in Java - 1

Conclusion

By the end of this post, you must be familiar with the reversal of Strings and how to achieve it using other classes of StringBuilder and StringBuffer. You can choose any method as per your convenience. Feel free to hop on whenever you feel stuck. Till then, keep practising and keep shining.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION