How to Reverse a String in Java


Using built-in reverse() method of the StringBuilder class

The best way to reverse a String in Java (for non-education purposes) is to use the reverse() method of the StringBuilder class. It reverse a string and is safe to use with Unicode characters.

String str = "codeahoy.com";

StringBuilder reversedStr = new StringBuilder(str).reverse();

System.out.println("Original: " + str);
System.out.println("Reversed: " + reversedStr);

This outputs:

Original: codeahoy.com
Reversed: moc.yohaedoc

Using traditional for loop to iterate from end to beginning of strings

Another way to reverse Strings in Java is by iterating through the string last to first, printing each character. Note that this is not safe for Unicode characters.

Let’s see how this done:

String str = "codeahoy.com";

for (int i = str.length()-1; i >= 0; i--) {
    System.out.print(str.charAt(i));
}

Output: moc.yohaedoc

Speak Your Mind