Reverse a String in Java

Reverse a String in Java

5 mins read3.4K Views Comment
clickHere
Updated on Sep 18, 2023 17:21 IST

Reversing a string is a common programming problem given while learning how to code and invoke logical thinking. However, there are more than one ways to solve this problem. The below article explains different ways to reverse a string in Java.

2022_05_Untitled-design-7.jpg

Strings in Java are immutable (can’t be changed) non-primitive data type that stores a sequence or array of characters. The reverse of a string means printing the character of a string from end to start. 

For more information, Read Strings in Java

Contents

2023_09_image-283-768x305-1.jpg

There are numerous ways to reverse a string in Java. So, let’s see how it’s done using various methods.

Different Ways to Reverse a String in Java

Following are the different ways to Reverse a String in Java

Creating a New String

Using this way, first, we’ll create a new string. Then, iterate through each character of the original string and put it in front of the new string made. Hence, the new string is the reverse of the original string.

Program:

 
class Create_New_String_Reverse_String
{
public static void main(String args[]) {
String str1 = "Shiksha Online";
System.out.println("Original string: "+str1);
int n = str1.length(); // caclulates length of String
String Reverse_String ="";
char ch;
for(int i=0;i<n;i++) {
//fetch each character
ch = str1.charAt(i);
//concatenates each character in front of the new string
Reverse_String = ch + Reverse_String;
}
System.out.println("Reversed string: "+Reverse_String); // Display the reversed String
}
}
Copy code

Output:

Original string: Shiksha Online
Reversed string: enilnO ahskihS
What is Wrapper Class in Java?
What is Wrapper Class in Java?
This article will teach you what is wrapper class and how wrapper objects are created. It will also teach you the concept of autoboxing and unboxing in java.
Multithreading in Java
Multithreading in Java
The below article goes through explaining the concepts of Multithreading in Java and its implementation. Let’s begin the tutorial.
Java Methods Explained (with Code)
Java Methods Explained (with Code)
The below java tutorial covers java methods with examples and explanations. It also goes through the declaration, implementation, types, and its uses.

Also Read: Variables in Java

Recursion

Apply recursion on an original string to reverse the string. Condition: 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 call the function again (recursively).

Program:

 
class Reverse_String_Recursion
{
static void Reverse(String str)
{
if ((str==null)||(str.length() <= 1))
System.out.println(str);
else
{
System.out.print(str.charAt(str.length()-1));
Reverse(str.substring(0,str.length()-1));
}
}
public static void main(String[] args) {
String str1 = "String Reverse using Recursion";
System.out.println("Original string: "+str1);
System.out.print("Reversed string: ");
// recursive function call to Reverse()
Reverse(str1);
}
}
Copy code

Output:

Original string: String Reverse using Recursion
Reversed string: noisruceR gnisu esreveR gnirtS

Also Read: Getting Started with Java Hello World Program

Using StringBuilder

One can use StringBuilder, which is a mutable brother of String. First, create a StringBuilder object and convert the given String to a StringBuilder object. StringBuilder has a reverse() function that provides reversed string which can later be converted into a string again using the tostring() function.

Program:

 
class StringBuilder_Reverse_String
{
public static void main(String[] args) {
String str = "Reverse String Using StringBuilder";
System.out.println("Original string: "+str);
// Declaring a StringBuilder and converting string to StringBuilder
StringBuilder reverseString = new StringBuilder(str);
reverseString.reverse(); // Reversing the StringBuilder
// Converting StringBuilder to String
String result = reverseString.toString();
System.out.println("Reversed string: "+result);
}
}
Copy code

Output:

Original string: Reverse String Using StringBuilder
Reversed string: redliuBgnirtS gnisU gnirtS esreveR

Also Read: Difference between JDK, JRE, and JVM

Using StringBuffer

One can also use StringBuffer, which is a mutable String. First, create a StringBuffer object and convert the given String to a StringBuffer object. StringBuffer also has a reverse() function that gives reversed string which can later be converted into a string again using the tostring() function.

Program:

 
class StringBuffer_Reverse_String
{
public static void main(String[] args) {
String str = "Reverse String Using StringBuffer";
System.out.println("Original string: "+str);
// Declaring a StringBuffer and converting string to StringBuilder
StringBuffer reverseString = new StringBuffer(str);
reverseString.reverse(); // Reversing the StringBuffer
// Converting StringBuffer to String
String result = reverseString.toString();
System.out.println("Reversed string: "+result);
}
}
Copy code

Output:

Original string: Reverse String Using StringBuffer
Reversed string: reffuBgnirtS gnisU gnirtS esreveR

Read: Implementing Array in Java

Character Swapping

First, a string converts into a character array using toCharArray(). Then apply a loop to swap the first character with the last, the second character with the second last, and so on. At last, using String.ValueOf() converts character array to string.

Program:

 
import java.util.*;
class Reverse_String_Swapping_Chars
{
public static void main(String[] args) {
String strs = "Reverse String using Character";
System.out.println("Original string: "+strs);
// Converting String to Character Array
char str[] = strs.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
}
}
Copy code

Output:

Original string: Reverse String using Character
Reversed string: retcarahC gnisu gnirtS esreveR

Read: Exception Handling in Java

Using ArrayList

First, we will convert the original string to a character array. Then, create an ArrayList object and add the original characters to the ArrayList. Afterwards, we will use the reverse() function in the collection framework to reverse the ArrayList. At last, print the characters in the Arraylist one by one using a for loop.

Program:

 
import java.util.*;
class Reverse_String_using_ArrayList
{
public static void main(String[] args) {
String strA = "Reverse String using ArrayList";
System.out.println("Original string: "+strA);
char str[] = strA.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));
}
}
}
Copy code

Output:

Original string: Reverse String using ArrayList
Reversed string: tsiLyarrA gnisu gnirtS esreveR

Read: Constructors in Java Explained

Using Stack

The concept of the stack in data structure follows last-in-first-out (LIFO). In this method, we’ll create a stack object and push the original string characters to it. Then, pop the elements out of the stack and print them.

Program:

 
import java.util.Stack;
class Stack_Reverse_String
{
public static void main(String args[]) {
String str = "Reverse String Using Stack";
System.out.println("Original string: "+str);
int n = str.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(str.charAt(i));
}
String reversedString = "";
// pop characters in reversed order
while(!stack.isEmpty()){
reversedString+=stack.pop();
}
System.out.println("Reversed string: "+reversedString); // Display the reversed string
}
}
Copy code

Output: 

Original string: Reverse String Using Stack
Reversed string: kcatS gnisU gnirtS esreveR

Read: Data Types in Java – Primitive and Non-Primitive Data Types Explained

XOR Operation

This way first converts the string into an array of characters. Then, we’ll put 2 pointers at the first and last element. Afterwards, we’ll swap the first and last characters using the XOR (^) operation, the second and second the last element, and so on. Finally, print the reversed character array by iteration.

For more, Read: Java Operators Explained

Program:

 
class XOR_Reverse_String
{
public static void main(String args[]) {
String str = "Reverse String using XOR Operations";
System.out.println("Original string: "+str);
// Converting String to Character Array
char[] str_array = str.toCharArray();
int low = 0;
int high = str_array.length - 1;
while (low < high) {
//Using XOR Operation
str_array[low] = (char) (str_array[low] ^ str_array[high]);
str_array[high] = (char) (str_array[low] ^ str_array[high]);
str_array[low] = (char) (str_array[low] ^ str_array[high]);
low++;
high--;
}
System.out.print("Reversed string: ");
//display reversed string
for (int i = 0; i < str_array.length; i++) {
System.out.print(str_array[i]);
}
}
}
Copy code

Output:

Original string: Reverse String using XOR Operations
Reversed string: snoitarepO ROX gnisu gnirtS esreveR

Also Read: 8 Most Important Data Structures Every Programmer Must Know

Conclusion

I hope you enjoyed learning about the above methods to reverse a string in Java. If you have any queries feel free to share them on the link below and keep learning.

Read: Top 160 Java Interview Questions and Answers for 2022

______________

Recently completed any professional courses/certifications from the market? Tell us what you liked or disliked in the course for more curated content.

Click here to submit its review with Shiksha Online.

FAQs

What is a String in Java?

Strings in Java are immutable (cannot be changed) non-primitive datatype that stores a sequence or array of characters.

What are Lists in Java?

Java has ArrayLists which are arrays that resize themselves as needed. A typical implementation is when the array is full, the array doubles in size.

What is Stack in Java?

Stack is a data structure in java that follows the last-in-first-out (LIFO) concept.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments