Reverse the String in Java

Reversing a string means to switch the ordering of the characters in a string. For example, the reverse of the string "Hello!" is "!olleH". There are many ways the reversal of a string can be done in Java.

Steps

Using a Buffer in JDK

  1. Use the reverse method of the StringBuffer class in the JDK. The code snippet for reverse method is as follows:

    public String reverse(String str) {
    if ((null == str) || (str.length() <= 1)) {
    return str;
    }
    return new StringBuffer(str).reverse().toString();
    }
  2. Appending to a StringBuffer: StringBuffer is an apt choice to create and manipulate dynamic string information. Reversal using StringBuufer is also an option.

    public String reverse(String str) {
    if ((null == str) || (str.length() <= 1)) {
    return str;
    }
    StringBuffer reverse = new StringBuffer(str.length());
    for (int i = str.length() - 1; i >= 0; i--) {
    reverse.append(str.charAt(i));
    }
    return reverse.toString();
    }
    }
  3. A recursive function can also be used to reverse a string.

    public String reverse(String str) {
    if ((null == str) || (str.length() <= 1)) {
    return str;
    }
    return reverse(str.substring(1)) + str.charAt(0);
    }
  4. CharArray can be used to reverse as follows:

    public String reverse(String str) {
    if ((null == str) || (str.length() <= 1)) {
    return str;
    }
    char[] chars = str.toCharArray();
    int length = chars.length - 1;
    for (int i = 0; i < length; i++) {
    char tempVar = chars[i];
    chars[i] = chars[length];
    chars[length--] = tempVar;
    }
    return new String(chars);
    }

Using the Byte Array

  1. Use the following code to reverse the string via an array.

Related Articles