Java Programming Tutorials

Java programming tutorials with many code examples!

Java Reverse String in 2 ways

Java Reverse String in 2 ways

Java String doesn’t have reverse method, so it may not be immediately apparent how to reverse a string in Java. Here are two ways do do it.

Reverse String using StringBuilder

The simplest and cleanest way to do it is to use StringBuilder class, because it has reverse methods, which we can reuse:

private static String withStringBuilder(String s) {
    return new StringBuilder(s).reverse().toString();
}

Reverse using char array

Another way, but a bit more complex, is to implement the reverse method by ourselves. The simplest and fast algorithm is to go from both sides and swap current characters:

private static String charArrayReverse(String s) {
    char[] chars = s.toCharArray();
    for (int i = 0, n = s.length()-1; i < n; ++i, --n) {
        char c = chars[i];
        chars[i] = chars[n];
        chars[n] = c;
    }
    return new String(chars);
}

Complete example

package com.farenda.java.lang;

public class ReverseString {

    public static void main(String[] args) {
        String saluton = "Saluton, la mondo!";
        System.out.println("Original: " + saluton);

        withStringBuilder(saluton);

        charArrayReverse(saluton);
    }

    private static void withStringBuilder(String s) {
        String reversed = new StringBuilder(s).reverse().toString();
        System.out.println("Reversed 1: " + reversed);
    }

    private static void charArrayReverse(String s) {
        char[] chars = s.toCharArray();
        for (int i = 0, n = s.length()-1; i < n; ++i, --n) {
            char c = chars[i];
            chars[i] = chars[n];
            chars[n] = c;
        }
        String reversed = new String(chars);
        System.out.println("Reversed 2: " + reversed);
    }
}

The above code produces the following output:

Original: Saluton, la mondo!
Reversed 1: !odnom al ,notulaS
Reversed 2: !odnom al ,notulaS
Share with the World!