Reverse a string in Java

To reverse a string in Java, you can use the StringBuilder class, the StringBuffer class, or convert the string to a character array and swap characters from the beginning and end of the array.


Here's an example using StringBuilder:


String originalString = "Hello, World!";
StringBuilder reversedString = new StringBuilder(originalString).reverse();
System.out.println("Original string: " + originalString);
System.out.println("Reversed string: " + reversedString);


And here's an example using a character array:


String originalString = "Hello, World!";
char[] charArray = originalString.toCharArray();
int length = charArray.length;

for (int i = 0; i < length / 2; i++) {
    char temp = charArray[i];
    charArray[i] = charArray[length - 1 - i];
    charArray[length - 1 - i] = temp;
}

String reversedString = new String(charArray);

System.out.println("Original string: " + originalString);
System.out.println("Reversed string: " + reversedString);


Both of these examples will output:

Original string: Hello, World! Reversed string: !dlroW ,olleH


Note that using StringBuilder or StringBuffer is generally more efficient than converting to a character array, especially for longer strings, because they use mutable objects and avoid creating new strings or character arrays in memory.