Different ways to reverse a String in Java

In this article, we will discuss different approaches to reverse a String in Java.

  1. Reverse a String in Java using StringBuffer and StringBuilder library functions
  2. String reversal algorithms in Java
  3. Reverse a String using Recursion
  4. Reverse a String word by word in Java
  5. Reverse order of words in a String in Java

Reverse a String in Java

 

Reverse a String in Java using StringBuffer and StringBuilder library functions

Java provides library methods in StringBuffer and StringBuilder to reverse a String.

String reversal can be done as follows :


new StringBuffer("topjavatutorial").reverse().toString()

new StringBuilder("topjavatutorial").reverse().toString()

Here is an example:
package com.topjavatutorial;

public class StringReverse {

  public static void main(String[] args) {
    String str = "topjavatutorial";
    System.out.println(new StringBuilder(str).reverse().toString()); // lairotutavajpot
  }
}

 

String reversal algorithms in Java

During interviews, mostly interviewee are asked to write the program without using library functions.

Since String is immutable in Java, its not possible to change its contents. So, we have to create a new String that would hold the characters in reverse order.

This can be done using iterating over the characters of the String in reverse order.

package com.topjavatutorial;

public class StringReverse {

  public static void main(String[] args) {
    String str = "topjavatutorial";
    System.out.println(reverse(str)); // lairotutavajpot
  }

  private static String reverse(String str){
    char[] arr = str.toCharArray();
    String rvStr="";
    for(int i=arr.length-1;i>=0;i--)
      rvStr+=arr[i]; // Should use StringBuilder instead.. see below example
    return rvStr;
  }
}

 
Here is the program for the same using StringBuilder.

We have also used a String charAt() function, but that isn’t essential to the program logic and you may instead use a character array with a loop as shown in previous example.

package com.topjavatutorial;

public class StringReverse {

  public static void main(String[] args) {
    System.out.println("Reverse of string topjavatutorial is = " + reverseString("topjavatutorial") );
  }

  public static String reverseString(String source){
    int length= source.length();
    StringBuilder dest = new StringBuilder(length);
    
    for(int i=source.length()-1;i>=0;i--){
      dest.append(source.charAt(i));
    }
    
    return dest.toString();
  }
  
}


 

Output :


Reverse of string topjavatutorial is = lairotutavajpot

 

Reverse a String using Recursion

In below example, the function recursively adds the last character of the string to the end and reverses rest of the String

package com.topjavatutorial.app;
 
import java.util.Scanner;
 
public class StringReverse {
 
    public static void main(String[] args) {
 
        System.out.println("Enter a String: ");
        Scanner sc = new Scanner(System.in);
        String str = sc.next();
        sc.close();
        System.out.printf("Reverse of %s is %s", str, reverse(str));
    }
 
    public static String reverse(String str) {
 
        if ((null == str) || (str.length() <= 1)) {
            return str;
        }
        // recursively add first char at end and reverse rest of the string
        return reverse(str.substring(1)) + str.charAt(0);
    }
 
}

Output :

Enter a String:
hello
Reverse of hello is olleh
 

Reverse a String word by word in Java

Here, we reverse each word in a String, but the order of the words remains the same.
For example,


Hello World -> olleH dlroW 

package com.topjavatutorial;

public class StringReverse {

  public static void main(String[] args) {
    String str = "Hello World";
    System.out.println(reverse(str));
  }

  private static String reverse(String originalString) {
    String[] words = originalString.split("\\s+");
    String reverseString = "";
    for (int i = 0; i < words.length; i++) {
      String word = words[i];
      String reverseWord = new StringBuilder(word).reverse().toString();
      reverseString += " " + reverseWord;
    }
    return reverseString.toString().trim();
  }
}

 
Here is another approach for the same using StringTokenizer :
package com.topjavatutorial;

import java.util.StringTokenizer;

public class StringReverse {

  public static void main(String[] args) {
    String str = "Hello World";
    System.out.println(reverse(str));
  }

  private static String reverse(String str){
    StringBuilder rvstr = new StringBuilder();
    StringTokenizer st = new StringTokenizer(str, " ");
      while (st.hasMoreTokens()) {
          StringBuilder thisToken = new StringBuilder(st.nextToken());
          rvstr.append(thisToken.reverse() + " ");
      }
      return rvstr.toString();
  }
}


 

Reverse order of words in a String in Java

Here, only the order of the words in the String is reversed.

For example,


Hello World -> World Hello 

package com.topjavatutorial;

public class StringReverse {

  public static void main(String[] args) {
    String str = "Hello World";
    System.out.println(reverse(str)); 
  }

  private static String reverse(String originalString) {
    StringBuilder result = new StringBuilder();
    String[] words = originalString.split("\\s+");
    for (int i = words.length - 1; i >= 0; i--) {
      result.append(words[i]).append(' ');
    }
    return result.toString().trim();
  }
}

Here is another approach for the same that splits the String to List of words and uses Collections reverse() method.

package com.topjavatutorial;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class StringReverse {

  public static void main(String[] args) {
    String str = "Hello World";
    System.out.println(reverse(str));
  }

  private static String reverse(String str) {
    String delimiter = " ";
    List<String> words = Arrays.asList(str.split(delimiter));
    Collections.reverse(words);
    return String.join(delimiter, words);
  }
}

There are several approaches to reverse a String in Java. Here, we have tried to include a few of them.

If you would like to suggest any other approach, please add the same in the comment section.
 

© 2015 – 2018, https:. All rights reserved. On republishing this post, you must provide link to original post

2 comments

  1. venkat gummadi

    import java.util.Scanner;
    class Test3 {
    public static void main(String[] args) {
    System.out.println(“Enter A String value:”);
    String s=new Scanner(System.in).nextLine();
    char ch[]=s.toCharArray();
    for(int i=ch.length-1;i>=0;i–){
    System.out.print(ch[i]);
    }
    }
    }

  2. There is one more question asked in this areas.

    Reverse a string without using any variable ,string buffer, builder etc

    String str = “Hi Parag!”;
    for (int i = 0; i < str.length(); i++) {
    str = str.substring(1, str.length() – i)
    + str.substring(0, 1)
    + str.substring(str.length() – i, str.length());
    }

Leave a Reply.. code can be added in <code> </code> tags

%d bloggers like this: