Home / Development / Java / Reverse a String in Java
Reverse a String in Java

Reverse a String in Java

There are many ways of reversing a String in Java for whatever reason you may have. Today, we will look at a few simple ways of reversing a String in Java. For example, the string “Reverse Me” once reversed will be “eM esreveR”. We will start by looking at the most traditional method with the least help from external Java classes.

In the above code, we are basically reading in a String from the user afterwhich we will begin an iteration loop that will build the new reversed String. This is done in the “for” loop by obtaining the characters of the original String individually from the end by using the “charAt” function of the String class and concatenating them to a new String by using the “+” operator.

Another method which is also similar but uses the Java StringBuilder class instead:

Very similar to the previous method, the only difference is that we are using the “append” function of the Java StringBuilder class in the iteration loop instead to concatenate the characters to form the reversed String.

Of course there is still an easier shortcut to do it and that would be to simply use the Java StringBuilder class “reverse” function.

What we have seen above are just a few ways to reverse a String in Java. The point is that there are many possible ways to reverse a String in Java and at the end of the day, it boils down to individual requirements, restrictions and what works best for you.

  • Was this Helpful ?
  • yes   no

About Clinton De Silva

Clinton De Silva

One comment

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: