Basic Java Program : How to Reverse a String in Java ?

Today, we are going to learn the basic java program of How to Reverse a String in Java ?

Strings in java are sequence of characters or you can also call it as an array of character, e.g. “Java” string is an array of 4 character type. In Java, Strings object are immutable (unchangeable).

We are going to see all the ways to Reverse a String in Java. Here, we are discussing 4 different ways you can use to Reverse a String in Java. Let’s see with an example, What does Reversing a String means :

String = “JAVA”, then the ReversedString = “AVAJ”

Now, Let’s see all the possible ways :

Using Basic Java :

Let’s see How you can Reverse a String in Java using Basic Java Program of converting the String to character array and then traversing the character array in backwards.

Unlike in C/C++, we can’t traverse a string like an array of characters. In Java, we first need to convert the String to a char array by using toCharArray() method of the String class.

Once, the char array is formed, we can simply traverse the array backwards and concatenate, character by character to form a reverse String.

So, this is one of the way to Reverse a String in Java


 import java.util.*;
 import java.lang.*;
 import java.io.*;


 public class UsingForLoop
 {
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);
		String str = sc.nextLine();
		// Convert String to character array
		char ch[]=str.toCharArray();  

		// Reversing the String
    		String rev="";  
    		for(int i=ch.length-1;i>=0;i--){  
        		rev+=ch[i];  
    		}  
		System.out.println(rev);
	}
 }

Using String Builder :

Let’s see How you can Reverse a String in Java using String Builder Class in Java. Now, let me tell you about String Builder class in brief. String Builder in Java are also known as mutable or modifiable strings. As Strings in java are non mutable, StringBuilders are mutable.

Now, To Reverse a String in Java, we will convert the given String into String Builder and then you the reverse() method of the String Builder class. At last we convert the reversed String Builder object to a String object by using its toString() method. By this way you can Reverse a String in Java.

So, this is the code to Reverse a String in Java using StringBuilder class.


 import java.util.*;
 import java.lang.*;
 import java.io.*;


 public class UsingStringBuilder
 {
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);

		//Input the String we want to reverse
		String s = sc.nextLine();

		// Converting the String to a StringBuilder object
		StringBuilder sb = new StringBuilder(s);

		// Reversing the StringBuilder object using its reverse() method
		StringBuilder reverseSb = sb.reverse();

		// Converting StringBuilder back to String using toString() method
		String reverseString = reverseSb.toString();

		// Printing the Reversed String
		System.out.println(reverseString);
	}
 } 

Using String Buffer :

Let’s see How you can Reverse a String in Java using String Buffer Class in Java. Just like using String Builder class we can use String Buffer class to Reverse a String in Java.

StringBuffer Class in Java are also mutable or modifiable Strings. Now, you would be wondering what is the difference between StringBuffer and StringBuilder class in Java.

StringBuffer are thread-safe, synchronized Java class whereas, StringBuilder are not thread-safe and are also non-synchronized. But StringBuffer are Slow and StringBuilder are Fast. That’s why StringBuilder were built and are used to speed up the process if there is no need of thread safety and sync in your code.

So, this is the code to Reverse a String in Java using StringBuffer class.


 import java.util.*;
 import java.lang.*;
 import java.io.*;


 public class UsingStringBuffer
 {
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);

		//Input the String we want to reverse
		String s = sc.nextLine();

		// Converting the String to a StringBuffer object
		StringBuffer sb = new StringBuffer(s);

		// Reversing the StringBuffer object using its reverse() method
		StringBuffer reverseSb = sb.reverse();

		// Converting StringBuffer back to String using toString() method
		String reverseString = reverseSb.toString();

		// Printing the Reversed String
		System.out.println(reverseString);
	}
 } 

Using Stack :

There is one more to Reverse a String in Java and that is using the Stack Data structure present as a Collections in Java.

As we know, Stack uses LIFO that stands for “Last IN First OUT” to store data. By using this property of Java we can easily reverse a String. We will convert the String into a character array and then push every character while traversing the array first to last, and then, when you pop the data from stack the character will be returned in LIFO manner, i.e. popping the last pushed character first and so on.

So, let’s see the code to Reverse a String in Java using Stack Collection.


 import java.util.*;
 import java.lang.*;
 import java.io.*;


 public class UsingStack
 {
	public static void main (String[] args) throws java.lang.Exception
	{
		Scanner sc = new Scanner(System.in);

                //Input the String we want to reverse
		String s = sc.nextLine();

                //Convert String into char array using toCharArray() method
		char charArray[] = s.toCharArray(); 

                //Declare a stack and push each character in it
		Stack<Character> stack = new Stack<>();
		for(int i=0;i<s.length();i++){
			stack.add(charArray[i]);
		}
		String reverseString = "";

                // Empty the stack and concatinate the char to form string
		while(stack.empty()==false){
			reverseString += stack.pop();
		}

                // Print the reversed string
		System.out.println(reverseString);
	}
 }

Leave a Comment

Your email address will not be published. Required fields are marked *