Reverse a String in Java

Educational infographic highlighting approaches to reverse strings in Java. Covering StringBuilder, StringBuffer, split method char array manipulation, and toString method.

Ways to Reverse a String in Java 

You may use a number of ways to reverse the strings in Java programs.

If you are working with mutable strings by using StringBuilder or StringBuffer class then these classes have a built-in reverse method. For example:

String rev_me = "Hello, World!";

//By StringBuilder class
StringBuilder reversed = new StringBuilder(rev_me).reverse(); 
String result = reversed.toString();

If using strings based on a String class, it has a built-in method for reversing a string. In that case, you may create new objects and reverse a string by writing your own code.

In the following section, I will show you how to reverse a string by using the following ways with Java code:

  1. By StringBuilder Class
  2. By StringBuffer classto
  3. toCharArray method
  4. By split method
  5. Using toString method

An example of string reversing by StringBuilder Class

This can be the simplest way of reversing a string. Especially, if you are working with mutable strings and your program uses StringBuilder based strings then using its reverse method is handy.

See the following program for using the reverse method:

public class demo_tst {

          public static void main(String args[]) {

                 StringBuilder sBuiRev = new StringBuilder("String Reverse Demo");

                 System.out.println("Before SB reverse: " +sBuiRev);

                 //Using reverse() method

                 sBuiRev.reverse();

                 System.out.println("After SB reverse() method: " +sBuiRev);

                }

}

The Output:

Before SB reverse: String Reverse Demo

After SB reverse() method: omeD esreveR gnirtS

So, simply use the:

Str.reverse()

will reverse the order of sequence in the specified string.

With StringBuffer class

The StringBuffer class has the same method and you may reverse a string just like in the above example. Just change the class name from StringBuilder to StringBuffer and you are done. See this program:

public class demo_tst {

          public static void main(String args[]) {

                 StringBuffer sBuffRev = new StringBuffer("StringBuffer");

                 System.out.println(sBuffRev);

                 //Using reverse() method

                 sBuffRev.reverse();

                 System.out.println(sBuffRev);

                }

}

The Output:

StringBuffer

reffuBgnirtS

No, I use String class – how to reverse it?

Well, you have to do a little work in that case for reversing a string. One of the solutions can be using the charAt with string length method.

The Java charAt() method returns the character in the specified string for the given index number. The index of a string starts at zero.

So, the solution is to get the specified string that needs to be reversed character by character and concatenate to a new string object from the last to the first character.

See the code below where a user is asked to enter a string (by using Scanner class).

import java.util.Scanner;

public class demo_tst {

          public static void main(String args[]) {

           Scanner readStr = new Scanner(System.in);  // Reading from System.in

                

           System.out.println("Enter a String to reverse: ");



           String str = readStr.nextLine();              



                String strRev = "";

               for(int x = str.length() -1; x>=0; x--){

                     strRev = strRev + str.charAt(x);

               }

            

               System.out.print("The reversed string: " + strRev );

               readStr.close();



                }

}

As I entered different sentences to be reversed, the following is the output:

Enter a String to reverse:

Hello Java

The reversed string: avaJ olleH

Enter a String to reverse:

Hi Number 25

The reversed string: 52 rebmuN iH

Enter a String to reverse:

Ok the fina() test +

The reversed string: + tset )(anif eht kO

So how exactly does it work?

  • In the for loop, the variable is assigned the value of string length -1, as string index starts at 0.
  • The loop should keep on executing until it reaches a value greater than zero.
  • In each iteration, the variable value is decremented by -1.
  • In the body of the loop, the charAt method is used that return the character in the input string for the current value of the variable (that acts as the index position).
  • The returned character is concatenated to a new String object that was initially declared as an empty string.

Reversing by toCharArray method of String class

You may also use the toCharArray method of the String class that converts a string to a new character array.

So, the string that you want to reverse is first converted to a character array and then you may use this solution to get a reversed string.

public class demo_tst {

          public static void main(String args[]) {

            String strToRev = "Reverse me";               
              char[] strArr= strToRev.toCharArray();        

               String strRev = "";
                for(int x = strArr.length -1; x>=0; x--){
                 strRev = strRev + strArr[x];
                }

               System.out.print("Original String: " + strToRev +"\n" );
               System.out.print("The reversed string: " + strRev );
         }
}

Java reverse string

Using the split method of String class to reverse a string

Well, this is an even more interesting solution. In that way, by little tweaking the code, you may reverse the given string letter by letter or word by word and even by sentences.

By the way, the String class split method is used to break the specified string by the given regex and returns an array of broken strings.

See this example where the given string is reversed by using the split method:

public class demo_tst {

          public static void main(String args[]) {
                  String srcStr= "Reverse by split";

           //Splitting the string
           String[] arrStr = srcStr.split("");

           String strRev = "";
            for(int i=arrStr.length-1;i>=0;i--){
             strRev = strRev + arrStr[i];
            }
             System.out.print("Source string: " + srcStr +"\n");
             System.out.print("The reversed string after split: " + strRev );
            }

}

Java reverse string split

Reversing by words using the split method

In the above example, the string is reversed character by character. Only changing the regex to space for this example and you will see the returned result is reversed word by word.

public class demo_tst {

        public static void main(String args[]) {

         String srcStr= "Spit for reversing";

         //Splitting the string
         String[] arrStr = srcStr.split("\\s");

         String strRev = "";
         for(int i=arrStr.length-1;i>=0;i--){
         strRev = strRev + arrStr[i] + " ";
          }

          System.out.print("Source string: " + srcStr +"\n");
          System.out.print("The reversed string after split: " + strRev );
     }

}

The Output:

Source string: Spit for reversing

The reversed string after split: reversing for Spit

Notice this line in the for loop body:

strRev = strRev + arrStr[i] + ” “;

Space is also concatenated in each iteration, otherwise, the words are attached to each other without space.  For example, this would have the result if no space was used in concatenation:

The reversed string after split: reversingforSpit

Reversing a paragraph – sentence by sentence using split method

Similarly, you may use the split method for reversing sentences in paragraphs. So, if you have long strings that contain paragraphs and you need to reverse by sentences rather than letters or words, then you may use the \\. (dot) regex.

public class demo_tst {

          public static void main(String args[]) {
              String srcStr= " Spit for reversing. Reverse the sentences in the paragraphs. For that, use the dot regex. Taken?";
               //Splitting the string
               String[] arrStr = srcStr.split("\\.");

               String strRev = "";
                 for(int i=arrStr.length-1;i>=0;i--){
                  strRev = strRev + arrStr[i] + ".";
               }
                System.out.print("Source string: " + srcStr +"\n");
                System.out.print("The reversed string after split: " + strRev );
            }

}

The output of above code is:

Source string:  Spit for reversing. Reverse the sentences in the paragraphs. For that, use the dot regex. Taken?

The reversed string after split:  Taken?. For that, use the dot regex. Reverse the sentences in the paragraphs. Spit for reversing.

In that case, you need to make sure that source paragraph’s sentences are separated by dots (full stop). Or you may tweak the code by adding more regex like if paragraphs contain question marks or other characters at the end of the string.

For question marks, you may use the following regex in the split method:

Str.split(“\\.|\\?”);

I am sure, you will also find out how to add the question mark in the reversed string as well!

Using toString method with the reverse method of StringBuilder class

Well, sounds back to the first two solutions. Yes, a little bit. But in that case, the resultant reversed string is still the mutable String object.

In that case, the reverse method of StringBuilder is used along with toString method. See the demo below:

public class demo_tst {

          public static void main(String args[]) {
                  String srcStr= "reverse it";
                  String revString = new StringBuilder(srcStr).reverse().toString();    
                  System.out.print("After toString and reverse: " + revString );
            }
}

The output:

After toString and reverse: ti esrever

 

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we solve the mysteries of coding together!