TeachingBee

How To Reverse A String In Java: 5 Ways

how to reverse a string in java

The Java strings are sequence of characters that are which are enclosed by double quotes(“”). They are immutable, i.e once they are declared, they are unchangeable.String can also be described as an array beginning with the index zero and end with a null character (\0).

In this post we will look into various ways on how to reverse a string in Java. But first let’s see how we can declare Strings in Java.

Declaring Strings in Java

1. Using new Keyword:

Strings in Java may be declared by using the latest keyword

String stringExample = new String("how to reverse a string in Java");

// Using character array
char ch[]={'j','a','v','a'};
String stringExample2 = new String(ch);

2. Using String Literal

Strings can also be declared using string literal as follows:

String stringExample = "how to reverse a string in Java";

Properties Of String in Java

  1. Strings are immutable. Immutable simply is the word used to mean its unchangeable. Once a String objects are created, its value or state cannot be altered.
  2. Strings are saved in a particular memory location called String Pool inside the Java memory
  3. Strings are joined using”+” operator “+” operator, which allows overloading by the operator.
  4. To allow mutable strings to be used, Java has provided two classes. These include StringBuffer as well as StringBuilder.

How To Reverse a String in Java:

1. Using StringBuilder

String object is immutable to make it mutable we will use StringBuilder class. StringBuilder has an inbuilt function known as reverse() that reverses the string. So, we’ll use this function to reverse the StringBuilder. Finally, transform the reversed StringBuilder into String by using the built-in method toString().

public static void main(String[] args) {

    String originalString = "java how to reverse a string";
    System.out.println("Original string: " + originalString);

    //Converting string to StringBuilder

    StringBuilder originalStringBuilder = new StringBuilder(originalString);

    // Reversing the StringBuilder
    originalStringBuilder.reverse();

    // Converting StringBuilder back to String

    String reversedString = originalStringBuilder.toString();


    System.out.println("Reversed string: " + reversedString); // Printing the reversed String


}

2. Using toCharArray()

By using toCharArray() method, we will change the original string to the form of a character array. After that we will swap two characters one from starting of array other from end. Finally, using Strings in-bult method String.valueOf() we will convert character array to string.

public static void main(String[] args) {

    String originalString = "java how to reverse a string";
    System.out.println("Original string: " + originalString);


    // Converting String to Character Array
    char charArray[] = originalString.toCharArray();

    int start = 0, end = charArray.length - 1;

    while (start <= end) {
        // Swapping the characters
        char temp = charArray[start];
        charArray[start] = charArray[end];
        charArray[end] = temp;
        start++;
        end--;
    }

    //  Converting characterArray to String
    String reversedString = String.valueOf(charArray);
    System.out.println("Reversed string: " + reversedString); //  Printing the reversed String


}

3. Using StringBuffer

To convert immutable String object we will use StringBuffer class. Similar to StringBuilder class, StringBuffer also has an inbuilt function known as reverse() that reverses the string. So, we’ll use this function to reverse the StringBuffer. Finally, transform the reversed StringBuffer into String by using the built-in method toString().

The difference between StringBuilder and StringBuffer is that, StringBuffer is synchronized i.e. it is thread safe. It means two threads can’t call the methods of StringBuffer simultaneously.

public static void main(String[] args) {

    String originalString = "java how to reverse a string";
    System.out.println("Original string: " + originalString);

    //Converting string to StringBuffer

    StringBuffer originalStringBuffer = new StringBuffer(originalString);

    // Reversing the StringBuffer
    originalStringBuffer.reverse();

    // Converting StringBuffer back to String

    String reversedString = originalStringBuffer.toString();

    // Printing the reversed String
    System.out.println("Reversed string: " + reversedString);

}

4. Using Byte array

To get the reverse string using Java, we transform the original string into an array of byte values with the Java built-in method getBytes() and then create the new byte array for keeping the result. Next, we will store result in reverse order from original byte array to result output array. Finally we will construct String object from the output byte array using String constructor.

public static void main(String[] args) {

    String originalString = "java how to reverse a string";
    System.out.println("Original string: " + originalString);

    // Convert to Byte Array
    byte[] originalStringByteArray = originalString.getBytes();

    byte[] outputByteArray = new byte[originalStringByteArray.length];

    // Store the original byte array into new byte array
    for (int i = 0; i < originalStringByteArray.length; i++) {
        outputByteArray[i] = originalStringByteArray[originalStringByteArray.length - i - 1];
    }

    // Convert Back byte array to String
    String outputString = new String(outputByteArray);
    System.out.println("Reversed string: " + outputString);

}

5. Using recursion

Recursion is nothing but a process in which function calls itself directly or indirectly. In this approach, we will write a method which reverses the String by calling itself recursively. The base condition for this recursion will be when string is null or length is less than equal to 1.

// Recursive Function To Reverse A String

static void reverse(String originalString) {
    if ((originalString == null) || (originalString.length() <= 1))
        System.out.println(originalString);
    else {
        // Print the last character of string
        System.out.print(originalString.charAt(originalString.length() - 1));

        // Recur for remaining string.
        reverse(originalString.substring(0, originalString.length() - 1));
    }
}

public static void main(String[] args) {
    String originalString = "how to reverse a string in java";
    reverse(originalString);
}  

Conclusion

In this post we saw Strings and its properties in java and also saw various methods on how to reverse a string in java.

Got a question or just want to chat? Comment below or drop by our forums, where a bunch of the friendliest people you’ll ever run into will be happy to help you out!

90% of Tech Recruiters Judge This In Seconds! 👩‍💻🔍

Don’t let your resume be the weak link. Discover how to make a strong first impression with our free technical resume review!

Related Articles

ascii value in java

Print ASCII Value in Java

In this article we will into the ASCII table in C, exploring its various character sets—from control characters to printable characters, including letters, digits, and special symbols—and demonstrates how to

data hiding in java

Data Hiding In Java

In this article we will discuss data hiding in Java which is an important concept in object-oriented programming. We will cover So let’s get started. What is Data Hiding in

Why Aren’t You Getting Interview Calls? 📞❌

It might just be your resume. Let us pinpoint the problem for free and supercharge your job search. 

Newsletter

Don’t miss out! Subscribe now

Log In