Learnitweb

Java program to reverse a string without String class’s reverse() function.

We’ll use the following approach in this example:

  1. Create an empty StringBuffer for processing. We have used StringBuffer because string manipulation will create string objects in memory.
  2. Loop from end of the string to the beginning of the string. Purpose of the loop is to get each character from end of the string to the beginning of the string.
  3. Append each character to the StringBuffer.
  4. Convert StringBuffer to String object.
public class ReverseStringExample {
  public static void main(String[] args) {
    String str = "Hello World";
    System.out.println("String before reverse: " + str);
    StringBuffer revStrBuffer = new StringBuffer("");
    for(int i=str.length()-1;i>=0;--i){
      revStrBuffer.append(str.charAt(i));
    }
    String reverseString = revStrBuffer.toString();
    System.out.println("reverse string: " + reverseString);
  }
}

Output

String before reverse: Hello World
reverse string: dlroW olleH