Reverse a string in java

5 examples to reverse a string

There are many ways to reverse a string in java, this article will show you 5 examples how to reverse a string.

1)By the reverse function of StringBuffer or StringBuilder,


2)By charAt fucntion of String class


3)By toCharArray function of String class


4)Use the feature of stack


5)Use dichotomy to reverse string array


which one is the most efficient

It is easy to get there ideas to reverse a string, but which one is the most efficient,let’ have a test.

the result output as below

from the result we can find that the time consuming relationship of the five methods is: reverseString2>reverseString3>reverseString4>reverseString1>reverString5.

As the java office document said: The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java. For additional information on string concatenation and conversion, see Gosling, Joy, and Steele, The Java Language Specification.

so the reverseString2 is slower than reverseString3. The principle ofreverseString3 and reverseString4 is also by char concat, so they are slower than reverseString1. and the charAt efficient is slower than get char from array by index,so reverseString2>reverseString3>reverseString4>reverseString1. Next,check the StringBuffer source code

we can find that the StringBuffer reverse string by char array,and the recycle time is more than reverseString5,so reverseString1>reverseString5. The result is reverseString2>reverseString3>reverseString4>reverseString1>reverString5, reverString5 is the most efficient.