In this section, you will see how to reverse a string without using the predefined method reverse(). Here we have explained the two solutions for the string reverse using recursion and without using recursion.
Let’s see both solutions below:
Solution #1 : Using Recursion
ReverseStringWithRecursion.java
package com.javacodepoint.programs;
import java.util.Scanner;
public class ReverseStringWithRecursion {
//Main method
public static void main(String[] args) {
// String variable to take a string input from the user
String str = null;
// Creating scanner class object for reading user input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string to reverse: ");
// reading the string input
str = sc.next();
//Final output
System.out.println("Reverse of the given string is "+reverseString(str));
}
// Recursive method
public static String reverseString(String str) {
// return empty when string is empty
if (str.equals("")) {
return str;
}
return reverseString(str.substring(1)) + str.charAt(0);
}
}
OUTPUT:
Please enter a string to reverse:
javacodepoint
Reverse of the given string is tniopedocavaj
Solution #2 : Without Using Recursion
ReverseString.java
package com.javacodepoint.programs;
import java.util.Scanner;
public class ReverseString {
//Main method
public static void main(String[] args) {
//String variable to take a string input from the user
String str=null;
//Initializing string variable to hold the reverse of the string
String reverse="";
//Creating scanner class object for reading user input
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a string to reverse: ");
//reading the string input
str=sc.next();
//iterating the string from the last to beginning
for(int i=str.length()-1; i>=0; i--) {
//picking one by one character and concatenating it with reverse
reverse = reverse + str.charAt(i);
}
//Final output
System.out.println("The reverse of "+str+" is "+reverse);
}
}
OUTPUT:
Please enter a string to reverse:
example
The reverse of example is elpmaxe