Yuriy  Malikov Yuriy Malikov - 6 months ago 25
Java Question

Some magic with String and stringBuilder.reverse.toString

So i have naturally my revers should be "tor", but when I tried

String straight = stringBuilders[i].toString();
String reverse = stringBuilders[i].reverse().toString();
System.out.println("stringBuilders[i].reverse().toString() = " + stringBuilders[i].reverse().toString()
+ " reverse = " + reverse + " straight = " + straight +
" rev == str ? " + reverse.equals(straight));


I got such result

stringBuilders[i].reverse().toString() = rot, reverse = tor, straight = tor, rev == str? false


What kind of magic is it?
Why

rev == str ?
gives output as
false

How can be that

stringBuilders[i].reverse().toString() = rot, reverse = tor,

Answer

Your first problem might be that straight uses index j, while the rest of the code uses index i.

Here is your code as an MCVE (Minimal, Complete, and Verifiable example):

StringBuilder stringBuilder = new StringBuilder("tor");
String straight = stringBuilder.toString();
String reverse = stringBuilder.reverse().toString();
System.out.println("stringBuilders[i].reverse().toString() = " +  stringBuilder.reverse().toString() +
                   " reverse = " + reverse +
                   "    straight = " + straight +
                   " rev == str? " + reverse.equals(straight));

Output is:

stringBuilders[i].reverse().toString() = tor reverse = rot    straight = tor rev == str? false

That is not the output you showed.

Anyway, your main problem is that reverse():

Causes this character sequence to be replaced by the reverse of the sequence.

So, your first call to reverse() makes the stringBuilder have the value rot, which is also the value assigned to the reverse variable.

Your second call to reverse() in the print statement reverse it back to the value tor, which is then the value printed.