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:
[toc]

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.
package org.arpit.java2blog;

public class ReverseStringForMain {
    public static void main(String[] args) {
        String blogName = "java2blog";
        String reverse = "";
        for (int i = blogName.length() - 1; i >= 0; i--) {
            reverse = reverse + blogName.charAt(i);
        }
        System.out.println("Reverse of java2blog is: " + reverse);
    }
}

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.

package org.arpit.java2blog;

public class ReverseStringRecursive {
    public static void main(String[] args) {
        ReverseStringRecursive rsr = new ReverseStringRecursive();
        String blogName = "java2blog";
        String reverse = rsr.recursiveReverse(blogName);
        System.out.println("Reverse of java2blog is:" + reverse);
    }

    public String recursiveReverse(String orig) {
        if (orig.length() == 1)
            return orig;
        else
            return orig.charAt(orig.length() - 1) + 
                          recursiveReverse(orig.substring(0, orig.length() - 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.

package org.arpit.java2blog;

public class StringBufferReverse {

    public static void main(String[] args) {

        String blogName = "java2blog";
        StringBuffer sb = new StringBuffer(blogName);
        System.out.println("Reverse of java2blog is:" + sb.reverse());

    }
}

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.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

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 *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.