Reverse a String in Java

A string is a sequence of characters that behave like an object in Java. The string is one of the most common and used data structures after arrays. It is an object that stores the data in a character array.

For better clarity, just consider a string as a character array wherein you can solve many string-based problems.

To create a string object, the java.lang.String class is required. Java uses UTF -16 to represent a string. Strings are immutable so that their internal state remains constant after the object is entirely created. The string object performs various operations, but the most widely used one is reverse.

Reverse in Java

Example: HELLO string reverse and give the output as OLLEH

Different Ways to Reverse a String

Since the strings are immutable objects, you need to create another string to reverse them. The string class doesn't have a reverse method to reverse the string. It has a toCharArray() method to do the reverse.

By Using toCharArray()

The code below will help you understand how to reverse a string. By using toCharArray() method is one approach to reverse a string in Java.

The code also uses the length, which gives the total length of the string variable.

The for loop iterates till the end of the string index zero.

Code 

//ReverseString using CharcterArray.

public static void main(String[] arg) {

// declaring variable

String stringinput = "Independent";

        // convert String to character array

        // by using toCharArray

        char[] resultarray = stringinput.toCharArray();

        //iteration

        for (int i = resultarray.length - 1; i >= 0; i--)

         // print reversed String

            System.out.print(resultarray[i]);

}

Output

ReverseAStringInJava_1

FREE Java Certification Training

Learn A-Z of Java like never beforeEnroll Now
FREE Java Certification Training

By Using StringBuilder

Let us see how to reverse a string using the StringBuilder class. StringBuilder or StringBuffer class has an in-build method reverse() to reverse the characters in the string. This method replaces the sequence of the characters in reverse order. The reverse method is the static method that has the logic to reverse a string in Java.

In the code mentioned below, the object for the StringBuilder class is used. 

The StringBuilder objects are mutable, memory efficient, and quick in execution. But it also considers these objects as not thread-safe.

The object calls the in-built reverse() method to get your desired output.

This is a preferred method and commonly used to reverse a string in Java.

Code:

//ReverseString using StringBuilder.

public static void main(String[] arg) {

// declaring variable

         String input = "Independent";

         // creating StringBuilder object

        StringBuilder stringBuildervarible = new StringBuilder();

        // append a string into StringBuilder stringBuildervarible

        //append is inbuilt method to append the data

        stringBuildervarible.append(input);

        // reverse is inbuilt method in StringBuilder to use reverse the string 

        stringBuildervarible.reverse();

        // print reversed String

        System.out.println( "Reversed String  : " +stringBuildervarible);

}

Output:

ReverseAStringInJava_2

Alternatively, you can also use the StringBuffer class reverse() method similar to the StringBuilder. Both the StringBuilder class and StringBuffer class, work in the same way to reverse a string in Java. Considering reverse, both have the same kind of approach. Although, StringBuilder class is majorly appreciated and preferred when compared to StringBuffer class. The StringBuilder class is faster and not synchronized. These StringBuilder and StringBuffer classes create a mutable sequence of characters. To achieve the desired output, the reverse() method will help you. 

In Java, it will create new string objects when you handle string manipulation since the String class is immutable. The StringBuilder and StringBuffer classes are two utility classes in java that handle resource sharing of string manipulations. 

By Using While Loop or For Loop

Simply handle the string within the while loop or the for loop. Get the length of the string with the help of a cursor move or iterate through the index of the string and terminate the loop.

The loop prints the character of the string where the index (i-1).

The loop starts and iterates the length of the string and reaches index 0.

Code Using While Loop

// Java program to reverse a string using While loop

import java.lang.*;

import java.io.*;

import java.util.*;

public class strReverse {

    public static void main(String[] args)

    {

    String stringInput = "My String Output";   

    //Get the String length

    int iStrLength=stringInput.length();    

    //Using While loop

while(iStrLength >0)

{

System.out.print(stringInput.charAt(iStrLength -1)); 

iStrLength--;

}

    }

}

Output:

ReverseAStringInJava_3

Code Using For Loop

// Java program to reverse a string using For loop

import java.lang.*;

import java.io.*;

import java.util.*;

public class strReverse {

    public static void main(String[] args)

    {

    String stringInput = "My New String";  

    //Get the String length

    int iStrLength=stringInput.length();    

    //Using For loop

for(iStrLength=stringInput.length();iStrLength >0;-- iStrLength)

{

System.out.print(stringInput.charAt(iStrLength -1)); 

}

    }

}

Output:

ReverseAStringInJava_4

By Converting a String to Bytes

The getBytes() method will split or convert the given string into bytes. The temporary byte array length will be equal to the length of the given string. Get the bytes in reverse order and store them in another byte array.

In the code below, a byte array is temporarily created to handle the string. The getBytes() is also an in-built method to convert the string into bytes. There are two byte arrays created, one to store the converted bytes and the other to store the result in the reverse order.

 Code

//ReverseString using ByteArray.

public static void main(String[] arg) {

// declaring variable 

String inputvalue = "Independent";

        // getBytes() is inbuilt method  to convert string

        // into bytes[].

        byte[] strAsByteArray = inputvalue.getBytes();

        byte[] resultoutput = new byte[strAsByteArray.length];

        // Store result in reverse order into the

        // result byte[]

        for (int i = 0; i < strAsByteArray.length; i++)

        resultoutput[i] = strAsByteArray[strAsByteArray.length - i - 1];

        System.out.println( "Reversed String  : " +new String(resultoutput));

}

Output: 

ReverseAStringInJava_5.

By Using ArrayList Object

Using the built-in method toCharArray(), convert the input string into a character array. Then, in the ArrayList object, add the array's characters. The Collections class in Java also has a built-in reverse() function. Since the reverse() method of the Collections class takes a list object, use the ArrayList object, which is a list of characters, to reverse the list.

Copy the String contents to an ArrayList object in the code below. Then, using the listIterator() method on the ArrayList object, construct a ListIterator object. To iterate over the array, use the ListIterator object. It also helps iterate through the reversed list and printing each object to the output screen one-by-one.

Code

// Java program to Reverse a String using ListIterator

import java.lang.*;

import java.io.*;

import java.util.*; 

// Class of ReverseString

class ReverseString {

    public static void main(String[] args)

    {

        String input = "Reverse a String";

        char[] str = input.toCharArray();

        List<Character> revString = new ArrayList<>();

        for (char c : str)

            revString.add(c);

        Collections.reverse(revString);

        ListIterator li = revString.listIterator();

        while (li.hasNext())

            System.out.print(li.next());

    }

}

Output: 

ReverseAStringInJava_6

Full Stack Java Developer Course

The Gateway to Master Web DevelopmentExplore Course
Full Stack Java Developer Course

By Using StringBuffer

The String class requires a reverse() function, hence first convert the input string to a StringBuffer, using the StringBuffer method. Then use the reverse() method to reverse the string.

Code

// Java program to convert String to StringBuffer and reverse of string

import java.lang.*;

import java.io.*;

import java.util.*;

public class strReverse {

    public static void main(String[] args)

    {

        String str = "String";

        // conversion from String object to StringBuffer

        StringBuffer sbfr = new StringBuffer(str);

        // To reverse the string

        sbfr.reverse();

        System.out.println(sbfr);

    }

}

Output: 

ReverseAStringInJava_7

Get a firm foundation in Java, the most commonly used programming language in software development with the Java Certification Training Course.

Conclusion

String Objects in Java are immutable, which means unchangeable. Java works with string in the concept of String literal. When one reference variable changes its value of the String object, then it will affect all the reference variables.

The class that is more commonly used in java is the String class. In Java.lang.String class, there are many methods available to handle the string functions such as trimming, comparing, converting, etc. These methods also help you reverse a string in java.

You have seen different ways to reverse a string in java. By writing our logic to reverse the string and also used in-built method reverse(). There are few popular third-party tools or libraries such as Apache Commons available to reverse a string in java.

You also work with string to remove duplicate characters, reverse the words in the sentence.

If you are looking to master Java and perhaps get the skills you need to become a Full Stack Java Developer, Simplilearn’s Full Stack Java Developer Master’s Program will prove to be the perfect starting point. This 6-month bootcamp certification program covers over 30 today’s top Java and Full Stack skills.The curriculum sessions delivered by top practitioners in the industry and along with the multiple projects and interactive labs make this a perfect program to gain work-ready skills needed to grab today’s top software development job roles.

On the other hand, if you have any feedback for us or inputs on this “Reverse a string with Java” article, feel free to share your thoughts with us via comments in the section at the bottom of this page. Our experts will review them and share our responses to them as soon as possible. 

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.