Showing posts with label Reverse string in java. Show all posts
Showing posts with label Reverse string in java. Show all posts

Tuesday, May 30, 2023

How to Reverse a String in place in Java - Example

To reverse a string in place in Java, you can use the following example code:


public class ReverseString {
    public static void main(String[] args) {
        String str = "Hello, World!";
        char[] charArray = str.toCharArray();

        int start = 0;
        int end = charArray.length - 1;

        while (start < end) {
            // Swap characters
            char temp = charArray[start];
            charArray[start] = charArray[end];
            charArray[end] = temp;

            // Move start and end pointers
            start++;
            end--;
        }

        String reversedStr = new String(charArray);
        System.out.println("Reversed string: " + reversedStr);
    }
}

In this example, we first convert the given string str into a character array using the toCharArray() method. We then initialize two pointers: start pointing to the first character of the array, and end pointing to the last character of the array. 

We enter a loop that continues until the start pointer is less than the end pointer. In each iteration, we swap the characters at start and end positions using a temporary variable temp. After swapping, we increment the start pointer and decrement the end pointer to move inward through the array. Once the loop completes, we have reversed the string in place. 

We convert the modified character array back to a string using the String class constructor, passing the character array as an argument. Finally, we print the reversed string. When you run the code, the output will be:


Reversed string: !dlroW ,olleH


Note that the approach used in this example modifies the original character array in place. If you want to reverse a string without modifying the original, you can create a new character array or use other methods like StringBuilder or StringBuffer.