What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Reverse a String in Java with Example

  • Nov 27, 2021
  • 7 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Anisha Dhameja
Reverse a String in Java with Example

Java is a class-based, object-oriented programming language. It is one of the most versatile programming languages with advantages in almost every field such as systems, applications, web apps, APIs, and so on. It is a language that makes programmers write once and read anywhere (WORA) i.e., the Java code once compiled can run on all platforms that support Java without the need for recompilation. And therefore you can say that Java is a platform-independent language. It possesses various in-build data structures such as integer, float, boolean, etc. Whether you're struggling in java or searching for java assignment help, our experts are here to help you 24/7.

The string is one of those data structures highly preferred by any java developer while programming. Therefore, in this article, various methods to reverse the string in java with example code and output. But before that, let us have a brief introduction to strings as a data structure in java below.

 

What is String in Java?

Strings are very frequently used data structures by Java developers and hence play a very crucial and important role while programming. The string is an object which represents the sequence of characters. The basic functionality of a string is to store a text(set of characters) inside the quote. Once a value is assigned to a string, it can’t be changed, which means strings are immutable. The creation, manipulation functionalities of strings are performed using the String class. Below are some important properties of strings:

  1. Strings are immutable
  2. Strings are stored in a special memory location known as String Pool inside the Java memory
  3. Strings are concatenated using the “+” operator, hence supporting operator overloading.
  4. Strings cannot be compared using the “==” operator. For comparison of strings equals() method is used.
  5. For using mutable strings, Java has provided two classes, which are StringBuffer and StringBuilder.

 

For Example:

public class StringsByFavTutor {

   public static void main(String[] args) {

       String stringExample = "FavTutor";

       System.out.println(stringExample);

   }

}

 

Output:

Favtutor

 

How to Reverse String in Java?

Below are the nine common methods by which you can reverse a string in java: 

1) Using StringBuilder

To reverse a string in java, we can first convert it to StringBuilder which is nothing but a mutable stringClass StringBuilder provides an inbuilt function called reverse(), which reverses the given string and provides you with the final output. Therefore, we will call this inbuilt function reverse() to reverse the StringBuilder and later,  convert the reversed StringBuilder to String using the inbuilt function toString().

For example:

public class ReverseStringByFavTutor

{

   public static void main(String[] args) {


       String stringExample  =  "FavTutor";

       System.out.println("Original string: "+stringExample);


       // Declaring a StringBuilder and converting string to StringBuilder

       StringBuilder reverseString = new StringBuilder(stringExample);


       reverseString.reverse();  // Reversing the StringBuilder


       // Converting StringBuilder to String

       String result = reverseString.toString();


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


   }

}

 

Output

Original string: FavTutor

Reversed string: rotuTvaF

 

2) Swapping characters

Using this method, first, we will convert the original string to a character array using an inbuilt string function named toCharArray()Next, we will swap the first with the last character, the second with the second last character, and so on which will eventually generate the reverse of the given string. Lastly, using the in-build function named String.valueOf(), we will convert the reversed character array to string.

For example:

public class ReverseStringByFavTutor

{

   public static void main(String[] args) {


       String stringExample  =  "FavTutor";

       System.out.println("Original string: "+stringExample);


       // Converting String to Character Array

       char str[] = stringExample.toCharArray();

       int n = str.length; // length of character array

       int start=0,end = n-1;

       while(start<=end){

           // Swapping the characters

           char temp = str[start];

           str[start] = str[end];

           str[end] = temp;

           start++;

           end--;

       }


       //  Converting characterArray to String

       String reversedString = String.valueOf(str);


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


   }

}

 

Output:

Original string: FavTutor

Reversed string: rotuTvaF

 

3) Creating a new String

To reverse a string in java, we will create a new string and iterate in the original string using for loopWhile iterating, we will concatenate each character of the original string in the front of the new string. The new string formed will be the reversed form of the original string as shown in the example below:

For example:

public class ReverseStringByFavTutor

{

   public static void main(String[] args) {


       String stringExample  =  "FavTutor";

       System.out.println("Original string: "+stringExample);


       int n = stringExample.length(); // length of String

       String reversedString ="";

       char character;


       for(int i=0;i<n;i++){

           //extracts each character

           character= stringExample.charAt(i);

           //concatenates each character in front of the new string                 i.e. reversedString

           reversedString = character+reversedString;

       }

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


   }

}

 

Output

Original string: FavTutor

Reversed string: rotuTvaF

 

4) Using a List

In this method, initially, we will convert the original string to a character array using an inbuilt function toCharArray(). Then will create an ArrayList of Characters. and add all the characters of the string in the ArrayList. Java Collections Framework consists of class Collections which has an inbuilt method reverse() and therefore, we'll use this inbuilt method Collections and reverse the ArrayList.

For example:

import java.util.*;

public class ReverseStringByFavTutor

{

   public static void main(String[] args) {


       String stringExample = "FavTutor";

       System.out.println("Original string: "+stringExample);

       char str[] = stringExample.toCharArray();

       int n = str.length; // length of characterArray

       // Declaring ArrayList of Characters

       ArrayList<Character> list = new ArrayList<>();


       for(int i=0;i<n;i++){ // Iterating through characterArray and adding character into list

           list.add(str[i]);

       }

       Collections.reverse(list); // Reversing list

       int size = list.size(); // size of ArrayList


       System.out.print("Reversed string: ");

       for(int i=0;i<size;i++){

           // Printing characters from ArrayList in reversed manner

           System.out.print(list.get(i));

       }

   }

}

 

Output

Original string: FavTutor

Reversed string: rotuTvaF


5) Using Stack

Using this method, we will instantiate a Stack object of characters and push all the characters of the original string into the stack using the stack’s inbuilt function push()Since stack follows the principle of “First In Last Out”, characters will be popped out the characters in reversed order. Hence, we will create a new string and pop all characters from the stack, and concatenate them in the new string as shown in the below example

For example:

import java.util.Stack;


public class ReverseStringByFavTutor

{

   public static void main(String[] args) {


       String stringExample  =  "FavTutor";

       System.out.println("Original string: "+stringExample);

       int n = stringExample.length(); // length of String


       Stack<Character> stack = new Stack<>(); // Creating a stack object


       for(int i=0;i<n;i++){

           // inserting characters of string one by one

           stack.push(stringExample.charAt(i));

       }

       String reversedString = "";


       // popped characters will be in reversed order

       while(!stack.isEmpty()){

           reversedString+=stack.pop();

       }


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

   }

}

 

Output

Original string: FavTutor

Reversed string: rotuTvaF

 

6) Using StringBuffer

To reverse string, we can first convert it to StringBuffer which is nothing but a mutable string. Class StringBuffer provides an inbuilt function called reverse(), which reverses the StringBuffer. Later, we will convert the reversed StringBuffer to String using the inbuilt function toString(). Check out the below example for a better understanding of StringBuffer.

For example:

import java.util.*;

public class ReverseStringByFavTutor

{

   public static void main(String[] args) {


       String stringExample  =  "FavTutor";

       // Converting from String Object to StringBuffer

       StringBuffer reversedStringBuffer = new StringBuffer(stringExample);

       reversedStringBuffer.reverse(); // reversing string

       System.out.println("Original String: "+stringExample);

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

   }

}

 

Output

Original string: FavTutor

Reversed string: rotuTvaF

 

7) Using XOR operation

In this method, we will convert the original string into a character array using the function toCharArray(). Later, we will keep two-pointer low and high where low belong to starting index and high belongs to the ending index. By using the XOR (^) operator we will swap the first and last character, the second and second last character, and so on and print the reverse string by iterating through array characters as shown below

For example:

import java.util.*;

public class ReverseStringByFavTutor

{

   public static void main(String[] args) {


       String stringExample  =  "FavTutor";

       System.out.println("Original string: "+stringExample);


       // Converting String to Character Array

       char[] str = stringExample.toCharArray();


       int low = 0;

       int high = str.length - 1;


       while (low < high) {

           str[low] = (char) (str[low] ^ str[high]);

           str[high] = (char) (str[low] ^ str[high]);

           str[low] = (char) (str[low] ^ str[high]);

           low++;

           high--;

       }


       System.out.print("Reversed string: ");

       //display reversed string

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

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

       }

   }

}

 

Output

Original string: FavTutor

Reversed string: rotuTvaF

 

8) Converting to a byte array

To get the reverse string in java, we will convert the original string to a byte array using the java inbuilt function getBytes() and create a new byte array for storing the result. Further, we will insert the last element of the original byte array at index ‘0’ of the resulting byte array, the second last at index ‘1’, and so on and convert the resulting byte array to String by creating a new String object and passing the resulting byte array in the constructor.

For example:

import java.util.*;

public class ReverseStringByFavTutor

{

   public static void main(String[] args) {


       String stringExample  =  "FavTutor";

       System.out.println("Original string: "+stringExample);


       byte[] byteArray = stringExample.getBytes();


       byte[] result = new byte[byteArray.length];


       // Store result in reverse order into the

       // result byte[]

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

           result[i] = byteArray[byteArray.length - i - 1];


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

   }

}

 

Output

Original string: FavTutor

Reversed string: rotuTvaF

 

9) Using recursion

Reversing a string using recursion is one of the most interesting methods. Here, you have to define a function that accepts a single parameter i.e., the original string, and make it recursive in nature. The base condition of the function will be; if the string is null or length less than or equal to one then return the original string, else, print the last character of the string and recursively call the function. Check out the example below for a better understanding

 

For example: 

import java.util.*;

public class ReverseStringByFavTutor

{

   static void reverse(String stringExample)

   {

       if ((stringExample==null)||(stringExample.length() <= 1))

           System.out.println(stringExample);

       else

       {

           System.out.print(stringExample.charAt(stringExample.length()-1));

           reverse(stringExample.substring(0,stringExample.length()-1));

       }

   }


   public static void main(String[] args) {


       String stringExample  =  "FavTutor";

       System.out.println("Original string: "+stringExample);


       System.out.print("Reversed string: ");

       // recursive function call

       reverse(stringExample);

   }

}

 

Output

Original string: FavTutor

Reversed string: rotuTvaF

 

Conclusion

Strings are frequently used data structures in any programming language and hence require large manipulation methods to modify them. In this article, we have presented various methods in java to reverse a string. Some are manual methods, some are inbuilt functions, and some useful classes operate on the String objects. We recommend using these methods to make your program more efficient and optimized. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Anisha Dhameja
I am Anisha Dhameja, a computer engineering student and technical content writer. I am passionate to learn more and more about the rising technologies of this new world. It makes me elated to share the vast expanse of my knowledge through the content I make, to enrich the knowledge and guide the thinkers of tomorrow.