Reverse a string in Java

Ron picture Ron · Sep 27, 2011 · Viewed 1.1M times · Source

I have "Hello World" kept in a String variable named hi.

I need to print it, but reversed.

How can I do this? I understand there is some kind of a function already built-in into Java that does that.

Related: Reverse each individual word of “Hello World” string with Java

Answer

Daniel Brockman picture Daniel Brockman · Sep 27, 2011

You can use this:

new StringBuilder(hi).reverse().toString()

Or, for versions earlier than JDK 1.5, use java.util.StringBuffer instead of StringBuilder — they have the same API. Thanks commentators for pointing out that StringBuilder is preferred nowadays when there is no concurrency concern.