Sobes.tech
Junior — Middle

How can string reversal be implemented in memory?

sobes.tech AI

Answer from AI

In Java, a String is an immutable object, so a direct reversal of the string in memory is not possible. However, you can reverse a string using a character array (char[]), which can be modified. Here's an example of reversing a string using a character array:

public class StringReverser {
    public static String reverse(String input) {
        char[] chars = input.toCharArray();
        int left = 0;
        int right = chars.length - 1;
        while (left < right) {
            char temp = chars[left];
            chars[left] = chars[right];
            chars[right] = temp;
            left++;
            right--;
        }
        return new String(chars);
    }

    public static void main(String[] args) {
        String original = "hello";
        String reversed = reverse(original);
        System.out.println(reversed); // output: olleh
    }
}

Thus, we create a mutable array of characters, change the order of characters in it, and then create a new string from the modified array.