Java Program To Reverse a String

Reversing a string is a classic exercise that every developer encounters, whether in a technical interview or while performing data manipulation in a real-world application. In Java, because String objects are immutable (meaning they cannot be changed once created), we can't simply flip the characters in place on the original object. Instead, we have to create a new representation of the string.

The following program demonstrates the most common logic-based approach: converting the string into a character array and using the "two-pointer" technique to swap characters from the outside in.

public class ReverseString {
    public static void main(String[] args) {
        // Input string - this could come from a database, user input, or a file
        String str = "Hello, World!";

        // Call the reverseString method and print the result
        System.out.println("Original string: " + str);
        System.out.println("Reversed string: " + reverseString(str));
    }

    /**
     * Method to reverse a string using a two-pointer approach.
     * This is highly efficient as it performs the swap in O(n/2) time.
     */
    public static String reverseString(String str) {
        // Handle edge cases like null or empty strings
        if (str == null || str.isEmpty()) {
            return str;
        }

        // Convert the string to a character array so we can modify it
        char[] charArray = str.toCharArray();

        // Initialize variables for indices
        int left = 0;
        int right = charArray.length - 1;

        // Iterate through the character array and swap characters
        while (left < right) {
            // Swap characters at left and right indices using a temporary variable
            char temp = charArray[left];
            charArray[left] = charArray[right];
            charArray[right] = temp;

            // Move indices towards the center to meet in the middle
            left++;
            right--;
        }

        // Convert the character array back to a string and return it
        return new String(charArray);
    }
}
Common Mistake: Attempting to reverse a string using a simple for loop and concatenating characters (e.g., newString += str.charAt(i)). In Java, this creates a new String object in every iteration of the loop, which is very slow and memory-intensive for long strings.

This program defines a reverseString method that takes a string as input, converts it to a character array, and then iterates through the array to swap characters from both ends until the entire string is reversed. Finally, it returns the reversed string. The main method demonstrates how to use this method by passing a sample string and printing the original and reversed strings.

How the Logic Works

The algorithm used above is known as the Two-Pointer Technique. We place one pointer at the start (index 0) and another at the end (length - 1). As we move the start pointer forward and the end pointer backward, we swap the characters at those positions. This process stops when the pointers meet or cross in the middle, ensuring every character is moved exactly once.

Developer Tip: While the manual approach is great for interviews, in a professional production environment, you should use the built-in StringBuilder class. It includes a highly optimized .reverse() method: return new StringBuilder(str).reverse().toString();.
Watch Out: Always check for null values before performing operations on a string. Calling .toCharArray() or .length() on a null object will trigger a NullPointerException, crashing your application.
Best Practice: If you are working with strings that contain special characters like emojis or certain mathematical symbols (Unicode surrogate pairs), a simple character swap might break them. For globalized applications, consider using codePoints() to ensure multi-byte characters are handled correctly.

Real-World Applications

While reversing "Hello World" is a simple exercise, string manipulation like this is used in several practical scenarios:

  • Data Masking: Quickly obfuscating parts of a string for logging purposes.
  • Palindrome Checking: Determining if a word reads the same forward and backward (e.g., "radar").
  • Bioinformatics: Reversing DNA sequences (reversing "ATGC" to "CGTA") for genetic analysis.
  • UI Effects: Creating interesting visual text animations or "typewriter" effects in CLI tools.