Reverse a String in Java

This Java tutorial shows how to reverse the contents of a string.

To reverse the contents of a string, we will use the StringBuffer class which has a reverse() method that allows us to easily reverse the contents of the string.

To start we will create a String and place that String into a StringBuffer.

//Original String
String originalString = "Hello World";

//Create a StringBuffer from the original string
StringBuffer buffer = new StringBuffer(originalString);

Next, we will call the reverse method on the StringBuffer and convert the StringBuffer back to a String.
//Reverse the contents of the StringBuffer
buffer = buffer.reverse();

//Convert the StringBuffer back to a String
String reverseString = buffer.toString();

Below is the complete code for reversing the contents of a string.
//Original String String
originalString = "Hello World";

//Create a StringBuffer from the original string
StringBuffer buffer = new StringBuffer(originalString);

//Reverse the contents of the StringBuffer
buffer = buffer.reverse();

//Convert the StringBuffer back to a String
String reverseString = buffer.toString();

//Print the original and reverse string
System.out.println("original: " + originalString);
System.out.println("reverse : " + reverseString);

Below is the output from the sample code above:
original: Hello World
reverse : dlroW olleH


6 comments:

Anonymous said...

Great post. Extremely intuitive. Thank you. It was exactly what I was looking for.

Seshu said...

Very Nice and easy to understand for beginners I liked it.
Thank you very much I hope Posts like these will be very useful an d every one will like it.

Anonymous said...

Thanks dudeee.. ur the best...

Anonymous said...

thanks

Anonymous said...

really its so nice for beginners.

Anonymous said...

Thank you.It really helps!...

Post a Comment