Reverse a String

Classic two-pointer string reversal demo with copyable code and live output

Java Code
public class ReverseString {
    public static void main(String[] args) {
        String str = "Hello, world!";

        // Call the reverse method
        String reversed = reverseString(str);

        // Print original and reversed strings
        System.out.println("Original string: " + str);
        System.out.println("Reversed string: " + reversed);
    }

    // Method to reverse the string using two-pointer technique
    public static String reverseString(String str) {
        char[] chars = str.toCharArray(); // Convert to char array

        int left = 0;
        int right = chars.length - 1;

        // Swap characters until the two pointers meet
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;

            left++;   // move start forward
            right--;  // move end backward
        }

        return new String(chars); // Convert back to string
    }
}
    
Output
Original string: Hello, world!
Reversed string: !dlrow ,olleH