Java program to reverse a string that a user inputs. If the string is “hello” then, the output is “olleh.” Write a recursive function to print reverse of a given string.
Java Program Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public class JavaExample { public static String reverse(String input){ if(input.isEmpty()) return input; //else put the character at the beginning to the end //make a recursive call return reverse(input.substring(1))+input.charAt(0); } public static void main(String[] args) { String input = "Hello World"; String reversedString = reverse(input); System.out.println("Original String: " + input); System.out.println("Reversed String: " + reversedString); } } |
Output:
1 2 3 4 |
Original String: Hello World Reversed String: dlroW olleH |
User Inputs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
import java.util.Scanner; public class JavaExample { public static String reverse(String input){ if(input.isEmpty()) return input; //else put the character at the beginning to the end //make a recursive call return reverse(input.substring(1))+input.charAt(0); } public static void main(String[] args) { Scanner sc=new Scanner(System.in); System.out.print("Original String: "); String input = sc.nextLine(); String reversedString = reverse(input); System.out.println("Reversed String: " + reversedString); } } |
Output:
1 2 3 4 |
Original String: Hello World Reversed String: dlroW olleH |