Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to reverse a string

Short answer

String has no reverse() method, but StringBuilder does:

void main() {
    String reversed = new StringBuilder("Java").reverse().toString();
    IO.println(reversed);
}

Output:

avaJ

With a loop

You can also build the string manually by walking the characters from the end:

void main() {
    String text = "hello";
    var result = new StringBuilder();
 
    for (int i = text.length() - 1; i >= 0; i--) {
        result.append(text.charAt(i));
    }
    IO.println(result);
}

Output:

olleh

Reversing words

To reverse the order of words rather than letters, split the string and reverse the list:

void main() {
    var words = new ArrayList<>(List.of("one two three".split(" ")));
    Collections.reverse(words);
 
    IO.println(String.join(" ", words));
}

Output:

three two one

Emoji and rare characters

StringBuilder.reverse() handles characters made of two char values (surrogate pairs), such as most emoji, correctly. A manual loop over charAt() breaks them:

void main() {
    String text = "ok👍";
    IO.println(new StringBuilder(text).reverse());
    IO.println(text.length());
}

Output:

👍ko
4

The length is 4 although you see three characters: the emoji takes two char values.

Common mistake

Expecting reverse() to change the original string. Strings in Java are immutable — you have to keep the result:

void main() {
    String word = "abc";
    new StringBuilder(word).reverse();
    IO.println(word);
}

Output:

abc

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.