Reverse String in Java without using any Temporary String,Char or String Builder

kaibuki picture kaibuki · Sep 30, 2011 · Viewed 30.6k times · Source

Is it possible to reverse String in Java without using any of the temporary variables like String, Char[] or StringBuilder?

Only can use int, or int[].

Answer

stivlo picture stivlo · Sep 30, 2011
String reverseMe = "reverse me!";
for (int i = 0; i < reverseMe.length(); i++) {
    reverseMe = reverseMe.substring(1, reverseMe.length() - i)
        + reverseMe.substring(0, 1)
        + reverseMe.substring(reverseMe.length() - i, reverseMe.length());
 }
 System.out.println(reverseMe);

Output:

!em esrever

Just for the fun of it, of course using StringBuffer would be better, here I'm creating new Strings for each Iteration, the only difference is that I'm not introducing a new reference, and I've only an int counter.