String reverse example in java

This example show you how you can get the reverse of a string object with String and StringBuffer object.

package com.java.connect.string;
 
// String reverse example in java
public class StringRevreseExample {
    public static void main(String[] args) {
        // Using simple string object of java
        String s = "mahendra";
        // Start from the tell of string print each char
        String r = "";
        for (int i = s.length() - 1; i >= 0; i--) {
            r = r + s.charAt(i);
        }
        System.out.println("Normal string using String object : " + s);
        System.out.println("Reverse string using String object : " + r);
        // Using StringBuffer object of java
        StringBuffer buffer = new StringBuffer("mahendra");
        // Simply use the reverse method of StringBuffer object
        System.out.println("Normal string using StringBuffer object : " + buffer.toString());
        System.out.println("Reverse string using StringBuffer object : " + buffer.reverse());
    }
}

The output of above example will be as:

Normal string using String object : mahendra
Reverse string using String object : ardneham
Normal string using StringBuffer object : mahendra
Reverse string using StringBuffer object : ardneham