Java program to reverse a String

Previous
Next

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.

Previous
Next

One Response

  1. JIGME WANGDI June 5, 2020

Add Comment