Shashank Shekher Shashank Shekher - 1 year ago 84
Java Question

Reverse a String and store it in the same variable in Java using String class methods

Suppose there is a string variable

str = "A man is no one!"
, then i need the reverse of this string to be stored in same str variable as
"!eno on si nam A"
, without using any other object or variable. Could someone please provide the most optimized way to do this?

I already used below piece of code:

public static String reverseRecursively(String str) {
//base case to handle one char string and empty string
if (str.length() < 2) {
return str;
return reverseRecursively(str.substring(1)) + str.charAt(0);

Any other way of doing this?

Please note that I only want it using
String class methods

Answer Source

Try this.

new StringBuilder(str).reverse().toString()

While this does create a new StringBuilder instance, it doesn't store it in a variable, and it would be very tricky (if possible) to reverse the string without ANY new objects whatsoever.


Since you don't want to use anything but String methods, here's a simple way to do it with a loop instead, but again it still creates new objects.

char[] chars = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
    chars[str.length() - i - 1] = str.charAt(i);
String newStr = new String(chars);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download