May 02

Java Strings are immutable (cannot be changed) so reversing a String requires creating a new String.

A loop can be used to build the reversed string by adding the characters from original string in reverse order, but the StringBuilder class provides a reverse() method to do it for us.

The following example shows its usage.

String s = "The string to be reversed";
StringBuilder sb = new StringBuilder(s);
sb.reverse();
String reversed = sb.toString();

written by objects \\ tags: , ,


Leave a Reply

You must be logged in to post a comment.