Below is an example code that reverse a string. In this example we use StringBuffer.reverse()
method to reverse a string. In Java 1.5, a new class called StringBuilder
also has a reverse()
method that do just the same, one of the difference is StringBuffer
class is synchronized while StringBuilder
class is not.
And here is the string reverse in the StringBuffer
way.
package org.kodejava.lang;
public class StringReverseExample {
public static void main(String[] args) {
// The normal sentence that is going to be reversed.
String words =
"Morning of The World - The Last Paradise on Earth";
// To reverse the string we can use the reverse() method in
// the StringBuffer class. The reverse() method returns a
// StringBuffer so we need to call the toString() method to
// get a string object.
String reverse = new StringBuffer(words).reverse().toString();
// Print the normal string
System.out.println("Normal : " + words);
// Print the string in reversed order
System.out.println("Reverse: " + reverse);
}
}
Beside using this simple method you can try to reverse a string by converting it to character array and then reverse the array order.
And below is the result of the code snippet above.
Normal : Morning of The World - The Last Paradise on Earth
Reverse: htraE no esidaraP tsaL ehT - dlroW ehT fo gninroM
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024
Best solution I came across, short and simple ?