Java program to reverse a String

In this post,  we will see java program to reverse a String.
There are many ways to do reverse a String in java, some of them are:

Using for loop

  1. Declare empty String reverse. This will contain our final reversed string.
  2. Iterate over array using for loop from last index to 0th index
  3. Add character to String reverse while iterating.
When you run above program, you will get following output:

Reverse of java2blog is: golb2avaj

💡 Did you know?

You can use charAt(int index) to access individual character in String.

Using recursion

We can also use recursion to reverse a String in java. We will process last character of String and call recursive function for rest of the String. Base case of the recursion will be once the length of String is 1.

When you run above program, you will get following output:

Reverse of java2blog is:golb2avaj

Using StringBuffer

We can also simple use StringBuffer's reverse() method to reverse a String in java.

When you run above program, you will get following output:

Reverse of java2blog is:golb2avaj

Please go through java interview programs for more such programs.

Was this post helpful?

Comments

  1. great resource. I have learned java a bit but its forgetting very soon. it’s a good refresh for me

Leave a Reply

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