1. Introduction

Reversing a string is one of the common tasks in programming interviews. The task is to take a string and return it in reverse order. In this blog post, we are going to write a Java program to reverse a string using string manipulation techniques.

2. Program Steps

1. Import the Scanner class from the java.util package for user input.

2. Define the main class named StringReverser.

3. Inside the main class, define the main method.

4. Inside the main method, create an object of the Scanner class to take user input.

5. Prompt the user to enter the string they want to reverse.

6. Convert the input string to a char array.

7. Reverse the char array.

8. Convert the reversed char array back to a string.

9. Print the reversed string.

3. Code Program

import java.util.Scanner; // 1. Importing Scanner class for user input

public class StringReverser { // 2. Defining the main class

    public static void main(String[] args) { // 3. Defining the main method

        Scanner input = new Scanner(System.in); // 4. Creating Scanner object to take user input

        System.out.print("Enter the string to reverse: "); // 5. Prompting user to enter the string
        String str = input.nextLine(); // Storing the user input in variable str

        char[] charArray = str.toCharArray(); // 6. Converting the input string to char array

        // 7. Reversing the char array
        for (int i = 0, j = charArray.length - 1; i < j; i++, j--) {
            char temp = charArray[i];
            charArray[i] = charArray[j];
            charArray[j] = temp;
        }

        String reversedString = new String(charArray); // 8. Converting the reversed char array back to string

        System.out.println("Reversed String: " + reversedString); // 9. Printing the reversed string

        input.close(); // Closing the Scanner object to avoid memory leak
    }
}

Output:

Enter the string to reverse: Hello World!
Reversed String: !dlroW olleH

4. Step By Step Explanation

– Step 1: The Scanner class from java.util package is imported for user input.

– Step 2: The main class StringReverser is defined.

– Step 3: The main method, which is the entry point of the program, is defined inside the main class.

– Step 4: A Scanner object named "input" is created to facilitate user input.

– Step 5: The user is prompted to enter a string, and the input Hello World! is stored in the variable str.

– Step 6: The input string str is converted to a char array charArray.

– Step 7: The char array charArray is then reversed by swapping the characters at the beginning and end, moving towards the center.

– Step 8: The reversed char array is converted back to a string and stored in the variable reversedString.

– Step 9: Finally, the reversed string !dlroW olleH is printed to the console.

– Lastly, the Scanner object is closed to prevent any potential memory leak.