Java Program to Reverse a String

Introduction

Reversing a string is a common task in programming, often used in scenarios such as data manipulation, palindrome checking, and more. This guide will show you how to create a Java program that reverses a given string using different approaches.

Problem Statement

Create a Java program that:

  • Takes a string as input.
  • Reverses the string.
  • Displays the reversed string.

Example 1:

  • Input: "Hello"
  • Output: "olleH"

Example 2:

  • Input: "Java"
  • Output: "avaJ"

Approach 1: Using a for Loop

Java Program

import java.util.Scanner;

/**
 * Java Program to Reverse a String using for loop
 * Author: https://www.javaguides.net/
 */
public class ReverseStringForLoop {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Prompt the user for input
        System.out.print("Enter a string to reverse: ");
        String input = scanner.nextLine();

        // Step 2: Reverse the string using a for loop
        String reversed = reverseString(input);

        // Step 3: Display the reversed string
        System.out.println("Reversed string: " + reversed);
    }

    // Method to reverse a string using a for loop
    public static String reverseString(String str) {
        StringBuilder reversed = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            reversed.append(str.charAt(i));
        }
        return reversed.toString();
    }
}

Explanation

  • Input: The program prompts the user to enter a string.
  • Reversing: A for loop iterates through the string from the last character to the first, appending each character to a StringBuilder.
  • Output: The reversed string is then printed to the user.

Output Example

Enter a string to reverse: Hello
Reversed string: olleH

Approach 2: Using StringBuilder's reverse() Method

Java Program

import java.util.Scanner;

/**
 * Java Program to Reverse a String using StringBuilder
 * Author: https://www.javaguides.net/
 */
public class ReverseStringStringBuilder {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Prompt the user for input
        System.out.print("Enter a string to reverse: ");
        String input = scanner.nextLine();

        // Step 2: Reverse the string using StringBuilder's reverse method
        String reversed = new StringBuilder(input).reverse().toString();

        // Step 3: Display the reversed string
        System.out.println("Reversed string: " + reversed);
    }
}

Explanation

  • Input: The program prompts the user to enter a string.
  • Reversing: The StringBuilder class's reverse() method is used to reverse the string in a single line.
  • Output: The reversed string is then printed to the user.

Output Example

Enter a string to reverse: Java
Reversed string: avaJ

Approach 3: Using Recursion

Java Program

import java.util.Scanner;

/**
 * Java Program to Reverse a String using Recursion
 * Author: https://www.javaguides.net/
 */
public class ReverseStringRecursion {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        // Step 1: Prompt the user for input
        System.out.print("Enter a string to reverse: ");
        String input = scanner.nextLine();

        // Step 2: Reverse the string using recursion
        String reversed = reverseString(input);

        // Step 3: Display the reversed string
        System.out.println("Reversed string: " + reversed);
    }

    // Method to reverse a string using recursion
    public static String reverseString(String str) {
        if (str.isEmpty()) {
            return str; // Base case: return the string if it's empty
        }
        return reverseString(str.substring(1)) + str.charAt(0); // Recursive case
    }
}

Explanation

  • Input: The program prompts the user to enter a string.
  • Reversing: A recursive method is used to reverse the string. The method takes the first character of the string and appends it to the result of reversing the rest of the string.
  • Output: The reversed string is then printed to the user.

Output Example

Enter a string to reverse: Hello
Reversed string: olleH

Conclusion

This Java program provides multiple methods to reverse a string, demonstrating different techniques such as loops, StringBuilder, and recursion. Each approach has its own advantages, and the choice of method may depend on specific requirements, such as readability, performance, or coding style. These methods are useful for various string manipulation tasks in Java.

Comments