-->

Hello,This is me!

ITEngineer8995

Professional Coder Coding is my passion

Wednesday, October 14, 2020

Java Program To Reverse a String Entered by the User

  • October 14, 2020
  • by

  

Java Program To Reverse a String Entered by the User

In this Java Program, we reverse a string entered by the user

Logic :  String reversed = reverseString(str);

Step 1 : Import Scanner Class

Step 2 : Create main method

Step 3 : Create variable str

Step 4 : Ask user to enter the username

Step 5 : Create the object of the Scanner Class

Step 6 : Store the user entered username in the variable str

Step 7 : Close the scanner class to avoid memory lea

Step 8 : Apply the logic

Step 9 : Print the reversed string

Step 10 : Create reversedString method

Step 11 : Apply if condition which says if str is empty then reverse string

Step 12 : Call the function recursively 

Program :

import java.util.Scanner;

public class JavaExample2 {

    public static void main(String[] args)

    {

        String str;

        System.out.println("Enter your username:");

        Scanner sc = new Scanner(System.in);

        str = sc.nextLine();

        sc.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

For execution of the same do visit my Youtube Channel :

https://youtu.be/GUoz8dR5d1E


A blog full of codes of various languages like Java, .net, C, C++ etc with their outputs and some other IT stuff.

0 comments:

Post a Comment

ITEngineer8995
India

SEND ME A MESSAGE

Search This Blog

Powered by Blogger.

Pages