Java Program -6 : Reverse a String using Recursion in Java

in java •  7 years ago 

reverse.jpg

We will see two programs to reverse a string. First program reverses the given string using recursion and the second program reads the string entered by user and then reverses it.
To understand these programs you should have the knowledge of following core java concepts:

  1. substring() in java
  2. charAt() method

Example 1: Program to reverse a string
public class JavaExample {

public static void main(String[] args) {
    String str = "Welcome to Beginnersbook";
    String reversed = reverseString(str);
    System.out.println("The reversed string is: " + reversed);
}

public static String reverseString(String str)
{
    if (str.isEmpty())
        return str;
    //Calling Function Recursively
    return reverseString(str.substring(1)) + str.charAt(0);
}

}
Output:
The reversed string is: koobsrennigeB ot emocleW

Example 2: Program to reverse a string entered by user
import java.util.Scanner;
public class JavaExample {

public static void main(String[] args) {
    String str;
    System.out.println("Enter your username: ");
    Scanner scanner = new Scanner(System.in);
    str = scanner.nextLine();
    scanner.close();
    String reversed = reverseString(str);
    System.out.println("The reversed string is: " + reversed);
}

public static String reverseString(String str)
{
    if (str.isEmpty())
        return str;
    //Calling Function Recursively
    return reverseString(str.substring(1)) + str.charAt(0);
}

}
Output:
Enter your username:
How are you doing?
The reversed string is: ?gniod uoy era woH

Authors get paid when people like you upvote their post.
If you enjoyed what you read here, create your account today and start earning FREE STEEM!
Sort Order:  

this is helpful bro

thanks

carry on brother.i think i should take lessons from you

great