Reverse a string in java without using reverse function

Let’s learn to reverse a string in java without using reverse function.

Reverse a string in java without using reverse function

We can reverse a string without using reverse function using for loop and recursion.

Here’s the program to reverse a string using for loop.

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();
   }
}


Output:

Please enter a string: flowerbrackets
Reverse a string without using reverse function: stekcarbrewolf

Please enter a string: helloworld
Reverse a string without using reverse function: dlrowolleh


Let’s see program to reverse a string using recursion. Recursive function is one which calls itself.

import java.util.Scanner;
public class ReverseStringUsingRecursion 
{
   String reverseRecursive(String str)
   {
      if(str.length() == 0)
          return " ";
      return str.charAt(str.length() - 1) + reverseRecursive(str.substring(0, str.length() - 1));
   }
   public static void main(String[] args) 
   {
      ReverseUsingRecursion obj = new ReverseUsingRecursion();
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter a string: ");
      String strInput = sc.nextLine();    
      System.out.println("Reverse string using recursion: " + obj.reverseRecursive(strInput));
      sc.close();
   }
}


Output:

Please enter a string: helloworld
Reverse string using recursion: dlrowolleh

Please enter a string: java
Reverse string using recursion: avaj