Reverse a string in Java

Learn reverse a string in java with practical examples, diagrams, and best practices. Covers java, string development techniques with visual explanations.

How to Reverse a String in Java: A Comprehensive Guide

Hero image for Reverse a string in Java

Learn various methods to reverse a string in Java, from basic loops to advanced API usage, with detailed explanations and code examples.

Reversing a string is a common programming task that tests a developer's understanding of string manipulation and basic algorithms. In Java, there are several ways to achieve this, each with its own advantages and use cases. This article will explore the most popular and efficient methods, providing clear explanations and practical code examples.

Understanding String Immutability in Java

Before diving into reversal techniques, it's crucial to understand that String objects in Java are immutable. This means once a String object is created, its content cannot be changed. Any operation that appears to modify a string, such as reversal, actually creates a new string object with the modified content. This immutability has implications for performance, especially when dealing with frequent string manipulations.

flowchart TD
    A[Original String] --> B{Reverse Operation}
    B --> C[New Reversed String]
    C --"Original String remains unchanged"--> A

String Immutability during Reversal

Method 1: Using a for Loop

The most fundamental way to reverse a string is by iterating through it from the last character to the first and appending each character to a new string or a StringBuilder. This method provides a clear understanding of the underlying logic.

public class StringReversal {

    public static String reverseUsingLoop(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        StringBuilder reversedString = new StringBuilder();
        for (int i = str.length() - 1; i >= 0; i--) {
            reversedString.append(str.charAt(i));
        }
        return reversedString.toString();
    }

    public static void main(String[] args) {
        String original = "Hello World";
        String reversed = reverseUsingLoop(original);
        System.out.println("Original: " + original);
        System.out.println("Reversed: " + reversed);
    }
}

Reversing a string using a for loop and StringBuilder.

Method 2: Using StringBuilder.reverse()

Java's StringBuilder class provides a convenient reverse() method that does exactly what we need. This is often the most straightforward and efficient approach for reversing strings in Java.

public class StringReversal {

    public static String reverseUsingStringBuilder(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        StringBuilder sb = new StringBuilder(str);
        return sb.reverse().toString();
    }

    public static void main(String[] args) {
        String original = "Java Programming";
        String reversed = reverseUsingStringBuilder(original);
        System.out.println("Original: " + original);
        System.out.println("Reversed: " + reversed);
    }
}

Reversing a string using StringBuilder.reverse().

Method 3: Using toCharArray() and Swapping

Another approach involves converting the string to a character array, swapping characters from both ends towards the middle, and then converting the character array back to a string. This method can be useful for in-place reversal if you were working directly with a mutable character array.

public class StringReversal {

    public static String reverseUsingCharArray(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        char[] charArray = str.toCharArray();
        int left = 0;
        int right = charArray.length - 1;

        while (left < right) {
            // Swap characters
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;

            left++;
            right--;
        }
        return new String(charArray);
    }

    public static void main(String[] args) {
        String original = "Algorithm";
        String reversed = reverseUsingCharArray(original);
        System.out.println("Original: " + original);
        System.out.println("Reversed: " + reversed);
    }
}

Reversing a string by converting to a character array and swapping elements.

Method 4: Using Java 8 Streams (Advanced)

For a more functional programming approach, Java 8 streams can be used. This method is often more concise but might be less performant for very long strings due to the overhead of stream operations and boxing/unboxing characters.

import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class StringReversal {

    public static String reverseUsingStreams(String str) {
        if (str == null || str.isEmpty()) {
            return str;
        }

        return IntStream.range(0, str.length())
                        .mapToObj(i -> str.charAt(str.length() - 1 - i))
                        .map(String::valueOf)
                        .collect(Collectors.joining());
    }

    public static void main(String[] args) {
        String original = "Functional";
        String reversed = reverseUsingStreams(original);
        System.out.println("Original: " + original);
        System.out.println("Reversed: " + reversed);
    }
}

Reversing a string using Java 8 streams.

Performance Comparison

The choice of method often depends on factors like readability, performance requirements, and whether you need thread safety. For most general-purpose string reversals, StringBuilder.reverse() is the most efficient and idiomatic Java solution.

graph TD
    A["Start: Reverse String"] --> B{"Method Choice"}
    B -->|Simple & Fast| C["StringBuilder.reverse()"]
    B -->|Manual Control & Learning| D["For Loop with StringBuilder"]
    B -->|In-place (char array)| E["toCharArray() & Swapping"]
    B -->|Functional & Concise| F["Java 8 Streams"]
    C --> G[End]
    D --> G
    E --> G
    F --> G

Decision flow for choosing a string reversal method.