Java Program to Reverse a String using Recursion - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Java Program to Reverse a String using Recursion

Java Program to Reverse a String using Recursion

Java Program to Reverse a String using Recursion

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

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.