Languages
[Edit]
EN

Java - how to reverse a string

2 points
Created by:
ParaEagle
724

1. Overview

In this post we will take a look how to reverse a string in java. Of course there is more than one way to do it.

String example  = "ABCD"; // we have this string
String reversed = "DCBA"; // expected - reversed string

2. Reverse string with StringBuilder - the simplest way

Code example:

String example = "ABCD";
String reversed = new StringBuilder(example).reverse().toString();

System.out.println(example);  // ABCD
System.out.println(reversed); // DCBA

Output:

ABCD
DCBA

3. Reverse string iterative method

Code example:

public class JavaReverseStringExample2 {

    public static void main(String[] args) {
        String example = "ABCD";

        char[] arr = example.toCharArray();
        int j = arr.length - 1;

        for (int i = 0; i < arr.length / 2; i++, j--) {
            char tmp = arr[i];
            arr[i] = arr[j];
            arr[j] = tmp;
        }
        String reversed = new String(arr);

        System.out.println(example);  // ABCD
        System.out.println(reversed); // DCBA
    }
}

Output:

ABCD
DCBA

4. Reverse string recursive method

Code example: 

public class JavaReverseStringRecursive {

    public static void main(String[] args) {
        String example = "ABCD";
        String reversed = reverseStringRecursive(example);

        System.out.println(example);  // ABCD
        System.out.println(reversed); // DCBA
    }

    public static String reverseStringRecursive(String str) {
        if ((null == str) || (str.length() <= 1)) {
            return str;
        }

        return reverseStringRecursive(str.substring(1)) + str.charAt(0);
    }
}

Output:

ABCD
DCBA

5. Reverse string with Apache commons

Code example:

import org.apache.commons.lang3.StringUtils;

public class JavaReverseStringApacheCommons {

    public static void main(String[] args) {
        String example = "ABCD";
        String reversed = StringUtils.reverse(example);

        System.out.println(example);  // ABCD
        System.out.println(reversed); // DCBA
    }
}

Output:

ABCD
DCBA

NOTE:

How Apache commons StringUtils.reverse looks internally:

public class StringUtils {

    // ..

    public static String reverse(final String str) {
        if (str == null) {
            return null;
        }
        return new StringBuilder(str).reverse().toString();
    }

    // ..

}

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - String (popular problems)

Java - reverse string
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join