java program to print string in reverse order code example

Example 1: Reverse a string in java without using reverse function

// Reverse a string in java without using reverse function
import java.util.Scanner;
public class ReverseWithoutFunction 
{
   public static void main(String[] args) 
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string: ");
      String strInput = sc.nextLine();
      int len = strInput.length();
      String strReverse = "";
      System.out.println("Reverse a string without using reverse function: ");
      for(int a = len - 1; a >= 0; a--)
      {
         strReverse = strReverse + strInput.charAt(a);
      }
      System.out.println(strReverse);
      sc.close();
   }
}

Example 2: reverse a string in java

Solution 1 

public static String StrReverse(String str) {

String reverse="";

for(int i=str.length()-1; i >= 0; i--)

reverse += str.toCharArray()[i];

 

return  reverse;

}

 

Solution 2 (using string buffer)

public  static String  Reverse(String str) {

return new StringBuffer(str).reverse().toString());

}

Tags:

Java Example