Java how to reverse a String

In this post we will provide some examples on how to reverse a String in Java. Two of the three examples will use the standard Java libraries and the last will use Apache Commons.

Java how to reverse a String

Example 1:

The first example is the most verbose solution out of the three. It loops through the String in reverse and appends each char to a new String.

Example 2:

The next example uses the StringBuilder. It has a useful method reverse() which does exactly what we want.

Example 3:

The final example uses the Apache commons lang library. This is the most concise solution out of the three. You will first need to add the following dependency to your project.

After you have added the dependency, the StringUtils class has a static method called reverse() which does exactly that, reverse the string you provide.

Running any of the above examples will produce the following output:

Similar posts

  1. How to split a string by new line
  2. Check if an Array contains a certain value
  3. Get request using Unirest
  4. Parse JSON string to Java object

References

  1. StringBuilder API Documentation
  2. StringUtils API Documentation

Leave a Reply