Builder: StringBuilder.reverse mutates in place

reverse() rewrites the buffer's own characters back to front and returns the same StringBuilder instance rather than a new one, which is why the reference equality check afterwards is true. Any other reference to that builder would see the reversed content too.

Code
StringBuilder sb = new StringBuilder("Java");
StringBuilder same = sb.reverse();
System.out.println("Reversed: " + sb);
System.out.println("Same instance: " + (sb == same));
Output
Reversed: avaJ
Same instance: true
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms