Skip to content
Advertisement

How work stringBuilder.reverse?

I thought revers should be equal “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

Why?

rev == str ? gives output as false How can be that

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

Advertisement

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.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement