Print the given string in reverse order in Java

Understanding String Reversal

Reversing a string means changing its character order from end to start.

We will explore three different methods to reverse a string in Java.

Method 1: Using a Loop

This method iterates through the string from end to start and prints the characters.

public class ReverseStringLoop {
    public static void reverseString(String s) {
        for (int i = s.length() - 1; i >= 0; i--) {
            System.out.print(s.charAt(i));
        }
        System.out.println();
    }
    
    public static void main(String[] args) {
        String str = "hello";
        reverseString(str);
    }
}
            
Input: hello
Output: olleh

Method 2: Using Recursion

This method reverses the string using recursion.

public class ReverseStringRecursion {
    public static void reverseRecursively(String s, int index) {
        if (index < 0) {
            System.out.println();
            return;
        }
        System.out.print(s.charAt(index));
        reverseRecursively(s, index - 1);
    }
    
    public static void main(String[] args) {
        String str = "world";
        reverseRecursively(str, str.length() - 1);
    }
}
            
Input: world
Output: dlrow

Method 3: Using StringBuilder

This method uses the built-in StringBuilder reverse function to reverse the string.

public class ReverseStringBuilder {
    public static void main(String[] args) {
        String s = "example";
        StringBuilder sb = new StringBuilder(s);
        sb.reverse();
        System.out.println(sb.toString());
    }
}
            
Input: example
Output: elpmaxe