Home > Articles > Programming > Java

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Reversing a String by Character

String letters = "ABCDEF";
StringBuffer lettersBuff = new StringBuffer(letters);
String lettersRev =
lettersBuff.reverse().toString();

The StringBuffer class contains a reverse() method that returns a StringBuffer that contains the characters from the original StringBuffer reversed. A StringBuffer is easily converted into a String using the toString() method of the StringBuffer. So by temporarily making use of a StringBuffer, you are able to produce a second string with the characters of an original string in reverse order.

If you are using JDK 1.5, you can use the StringBuilder class instead of the StringBuffer class. The StringBuilder class has an API compatible with the StringBuffer class. The StringBuilder class will give you faster performance, but its methods are not synchronized; thus it is not thread-safe. In multithreaded situations, you should continue to use the StringBuffer class.

  • + Share This
  • 🔖 Save To Your Account