Java Program to Reverse a String

Reversing a string is one of the most commonly asked questions in introductory Java courses and interviews. It's not just the code that's important, but understanding the logic behind it. In this blog post, we will break down how to reverse a string in Java and discuss multiple methods to do so. 

What does "Reversing a String" mean? 

Reversing a string means that the last character of the original string becomes the first character of the new string, the second last becomes the second, and so forth. For example, if the original string is "JAVA", the reversed string will be "AVAJ". 

Method 1: Using StringBuilder 

Java’s StringBuilder class has a built-in method reverse() which can be utilized to reverse the string.

public class StringReversal {
    public static void main(String[] args) {
        String original = "JAVA";
        StringBuilder buffer = new StringBuilder(original);
        System.out.println(buffer.reverse());
    }
}

Output:

AVAJ

Method 2: Using a Character Array 

We can manually reverse the string by converting it to a character array and using a loop.

public class StringReversal {
    public static void main(String[] args) {
        String original = "JAVA";
        char[] chars = original.toCharArray();
        for (int i = chars.length - 1; i >= 0; i--) {
            System.out.print(chars[i]);
        }
    }
}

Output:

AVAJ

Method 3: Using Recursion 

Recursion is the process in which a method calls itself. Here's how you can use recursion to reverse a string.

public class StringReversal {

    public static String reverseString(String str) {
        if (str.isEmpty())
            return str;
        return reverseString(str.substring(1)) + str.charAt(0);
    }

    public static void main(String[] args) {
        String original = "JAVA";
        System.out.println(reverseString(original));
    }
}

Output:

AVAJ

Things to Remember

Immutable Strings: In Java, strings are immutable. This means once a string is created, it cannot be changed. When we reverse a string, we're actually creating a new string. 

Performance: While the recursive method is elegant, it isn't the most efficient, especially for longer strings. For optimal performance, use the character array method or the StringBuffer method. 

Unicode and Special Characters: When working with strings containing special characters or Unicode, some additional considerations might be required to ensure they are handled correctly. 

Conclusion

Reversing a string in Java is a foundational exercise that helps solidify your understanding of string manipulation and different programming techniques. Whichever method you choose to use, the key is to understand the logic behind it. Happy coding!

Related Java String Programs with Output

Comments