How to reverse the string? We will use the following different solutions for reversing the string. First we get a input from user using command line.

In the first solution of this problem we buffer the input string using the StringBuffer(String string) method. Then reverse this buffer and after reversing convert the buffer into string.

Program:

public class StringReverse
{
   public static void main(String[] args) 
{
      String str = "abcd";
      String reverse = new StringBuffer(str).reverse().toString();
      System.out.println("\nString before reverse: "+str);
      System.out.println("String after reverse: "+reverse);
}
}

Output:

String before reverse: abcd
String after reverse: dcba
String Reverse

There are another solution in which we converts the input string into a character array and show the array in reverse order.

Program:

import java.io.*;
import java.util.*;

public class StringReverse1 {
   public static void main(String[] args) {
      String str = "JAVA";
      char[] string = str.toCharArray();
      System.out.println("\nString before reverse: \n"+str);
      System.out.println("String after reverse: ");
      for (int i = string.length-1;i >= 0; i--) 
       System.out.print(string[i]);
   }
}

Output:

String before reverse:
JAVA
String after reverse:
AVAJ
String Reverse

Leave a Reply

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

Back to Top