How to reverse a string in Java


JavaViews 2042

This tutorial will guide you to understand how to reverse a string in Java using different methods. A string is a group of characters that terminates with ‘\0’. Hence reversing a string means displaying the sequence of characters in the reverse order. For example, if a string is “Welcome”, the reverse of the string is “emocleW”.

How to reverse a string in Java

Different methods on how to reverse a string in Java

How to reverse a string in Java

Reverse a string using StringBuilder/StringBuffer

The StringBuilder and StringBuffer class contain a static method reverse() that reverses the character sequence in the string. The below example shows how to reverse a string in Java using the StringBuilder. We first create an instance of StringBuilder by specifying the string that we want to reverse as a parameter to the StringBuilder class. Using the reverse() method, we can directly reverse the input string and then convert it to a string variable using the toString() method.

public class ReverseStringDemo {

  public static void main(String[] args) {
    String s = "Welcome";
    StringBuilder sb = new StringBuilder(s);
    sb.reverse();
    String text = sb.toString();
    System.out.println("Original string: " + s);
    System.out.println("Reversed string: " + text);

  }

}
Original string: Welcome
Reversed string: emocleW

The below is the same example using the StringBuffer class and reverse() method.

public class ReverseStringDemo {

  public static void main(String[] args) {
    String s = "Welcome";
    StringBuffer sb = new StringBuffer(s);
    sb.reverse();
    String text = sb.toString();
    System.out.println("Original string: " + s);
    System.out.println("Reversed string: " + text);

  }

}
Original string: Welcome
Reversed string: emocleW

Reverse a string using Reverse iteration – toCharArray()

Another method to reverse a string is by using  thetoCharArray() method of the String class. This method converts the string to an array of characters. Using the for loop in the reverse direction which means starting from the length of the array until 0, we can iterate through each character and decrement by 1 and append to a new string variable. The below example illustrates the reverse iteration using the toCharArray() method.

public class ReverseStringDemo {

  public static void main(String[] args) {
    String s = "Welcome";
    
    char[] ch = s.toCharArray();
    String text = "";
    for(int i=ch.length-1;i>=0;i--) {
      text = text + ch[i];
    }

    System.out.println("Original string: " + s);
    System.out.println("Reversed string: " + text);

  }

}
Original string: Welcome
Reversed string: emocleW

Reverse a string using ByteArray

We can also reverse a string in Java by converting the string to a byte array and then retrieve each byte within a for loop in reverse order. For this, we create another byte array to store the reversed string. Within for loop, we start retrieving every byte from the end until it reaches 0.

public class ReverseStringByteArray {

  public static void main(String[] args) {
    String s = "Java tutorial";
    byte[] bArray = s.getBytes();
    int len = bArray.length;
    
    byte[] newString = new byte[len];	
    
    for(int i=0;i<len;i++) {
      newString[i] = bArray[len-i-1];
    }
    System.out.println(new String(newString));
  }

}
lairotut avaJ

Using swapping concept

Another technique to reverse a string is to use the swapping concept along with a temporary variable. This is the same logic where we swap two variables using a temporary variable. Here, we use a for loop to swap the characters and store them in an array. The final character array will contain the reversed string.

public class ReverseStringSwap {

  public static void main(String[] args) {
    String s = "Java tutorial";
    char[] chArray = s.toCharArray();
    
    int l = 0;
    int r = chArray.length-1;
    
    for(l=0;l<r;l++,r--) {
      char t = chArray[l];
      chArray[l] = chArray[r];
      chArray[r] = t;
    }
    
    for(char ch: chArray)
      System.out.print(ch);

    System.out.println();
  }

}
lairotut avaJ

Using ArrayList object

We can also reverse a string in Java using the ArrayList object. First, we convert the string to an array of characters using the toCharArray() method. Next, we create an ArrayList of type Character and add the characters to the list using the for loop. Since ArrayList is a Collection, we can use its inbuilt method reverse() to reverse the characters in the list. Now the ArrayList contains the characters of the string in the reverse order. Using the ListIterator, we can print the reverse string by fetching individual characters from the list.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;

public class ReverseStringArrayList {

  public static void main(String[] args) {
    String s = "Java tutorial";
    
    //convert string to character array
    char[] ch = s.toCharArray();
    
    List<Character> l = new ArrayList<>();
    
    //Add the characters to the list
    for(char c:ch)
      l.add(c);
    
    //Reverse using Collections
    Collections.reverse(l);
    
    //Print the characters in the reverse order from the list
    ListIterator li = l.listIterator();
    while(li.hasNext())
      System.out.print(li.next());

  }

}
lairotut avaJ

Using Recursion

Another technique on how to reverse a string in Java is to use recursion. This means we need to call a function recursively or repeatedly until it meets a certain condition. In the below example, we create a recursive function reverseString() that we call repeatedly to return the characters in the string in the reverse order.

public class ReverseStringRecursion {
  
  String reverseString(String s) {
    if(s.length() == 0)
      return " ";
    return s.charAt(s.length()-1) + reverseString(s.substring(0,s.length()-1));
  }

  public static void main(String[] args) {
    ReverseStringRecursion r = new ReverseStringRecursion();
    String s = "Java tutorial";
    System.out.println("Original string: " + s);
    System.out.println("Reversed string: " + r.reverseString(s));
  }

}
Original string: Java tutorial
Reversed string: lairotut avaJ 

Using while loop – charAt() method

Below is another method on how to reverse a string in Java using a while loop. We can loop through every character in a string starting from the last letter within a while loop. For this, we initialize the loop variable ‘i’ as the length of the string and retrieve each character from the last position and decrement the loop variable.

public class ReverseStringDemo {

  public static void main(String[] args) {
    String s = "Welcome";
    System.out.println("Original string: " + s);
    
    System.out.print("Reversed string: ");
    int i = s.length();
    while(i>0) {
      System.out.print(s.charAt(i-1));
      i--;
    }
    

  }

}
Original string: Welcome
Reversed string: emocleW

You might be interested in reading another article on Reversing the String

Reference

Translate »