Skip to content

← Back to Overview

Java Program - String Reversal

Concept Explanation

What is it?

String reversal is the process of rearranging the characters of a string in the opposite order. For example, "Hello" becomes "olleH".

Why is it important?

It is a fundamental algorithm used in data processing, palindromic checks, and interview coding challenges.


Algorithm (Manual Method)

  1. Start
  2. Input a string str.
  3. Create an empty string reversed.
  4. Loop through str from the last character back to the first.
  5. Append each character to reversed.
  6. Display reversed.
  7. End

Implementations

import java.util.Scanner;

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

        System.out.print("Enter a string: ");
        String str = sc.nextLine();

        // Method 1: Using StringBuilder (Easy & Efficient)
        String reversedSB = new StringBuilder(str).reverse().toString();

        // Method 2: Manual Loop
        String reversedManual = "";
        for (int i = str.length() - 1; i >= 0; i--) {
            reversedManual += str.charAt(i);
        }

        System.out.println("Original: " + str);
        System.out.println("Reversed (StringBuilder): " + reversedSB);
        System.out.println("Reversed (Manual Loop): " + reversedManual);

        sc.close();
    }
}

Explanation

  • Java
  • StringBuilder: A mutable sequence of characters. Its .reverse() method is the most efficient way to reverse a string in Java.
  • charAt(i): Returns the character at index i.
  • Efficiency: In the manual loop, reversedManual += str.charAt(i) creates many temporary string objects. In professional applications, always prefer StringBuilder.

Complexity Analysis

  • Time Complexity: O(n) where n is the length of the string.
  • Space Complexity: O(n) to store the reversed string.

Practice Problems

Easy

  • Check if a string is a Palindrome (reads the same forward and backward).

Medium

  • Reverse each word in a sentence while keeping the word order the same.

Interview Tips

  • Explain why StringBuilder is preferred over simple string concatenation inside a loop (Immutability vs Mutability).

"Turn your strings around, and you might find a palindrome." - Anonymous