Write program to reverse a String without using reverse() method in Java?

Java 8Object Oriented ProgrammingProgramming

You can reverse a String in several ways, without using the reverse() function.

Using recursion − Recursion is the process of repeating items in a self-similar way. In programming languages, if a program allows you to call a function inside the same function, then it is called a recursive call of the function. You can reverse a string using recursive function as shown in the following program.

Example

import java.util.Scanner;
public class StringReverse {
   public static String reverseString(String str){
      if(str.isEmpty()){
         return str;
      }else{
         return reverseString(str.substring(1))+str.charAt(0);
      }
   }
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String value: ");
      String str = sc.next();
      String result = StringReverse.reverseString(str);
      System.out.println(result);
   }
}

Output

Enter a String value:
Tutorialspoint
tniopslairotuT

Converting to byte/character array: You can get a byte or, character array using the getBytes() or, toCharArray() methods respectively.

To reverse a given String

  • convert it into an array.
  • Reverse the elements of the array.
  • Create another String using the resultant array.

Example

import java.util.Scanner;
public class StringReverse {
   public static String reverseString(String str){
      //Converting to character array
      char ch[] = str.toCharArray();
      int n = ch.length;
      char result[] = new char[n];
      for(int i = 0; i<ch.length; i++) {
         result[n-1] = ch[i];
         n = n - 1;
      }
      return new String(result);
   }
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String value: ");
      String str = sc.next();
      String result = StringReverse.reverseString(str);
      System.out.println(result);
   }
}

Output

Enter a String value:
Tutorialspoint
tniopslairotuT
raja
Published on 02-Aug-2019 12:27:11
Advertisements