String manipulation is a crucial skill often required when working with textual data such as data analysis, extracting insights from the string, etc. Both the beginner and an experienced developer need to understand the concept and the working of string reversal is essential. In Java, you can build your custom logic, and use built-in methods or data structures to achieve this functionality.
Quick Outline
This article covers the following content:
- How to Reverse Strings Using Custom Logics?
- How to Reverse a String Using Built-in Methods?
- How to Reverse a String Using Data Structures
- How to Reverse a String Using Apache Common Lang?
- How to Reverse a String Using Recursion?
How to Reverse Strings Using Custom Logics?
One of the methods of string reversal in Java is to implement custom logic. For this purpose, use CharArray, chatAt() method, loop statements, etc. This section discusses and implements the logic for reversing a string in Java using a manual approach:
Method 1: Using the While loop And charAt()
In this code snippet, the two string variables are created. The “reverseString” stores the reversed string. The “len” variable stores the total length of the “originalString” variable. Similarly, the boolean variable “check” is used by the while loop for iterations:
String originalString="welcome to JavaBeat", reverseString="";
int len=originalString.length()-1;
Boolean check=true;
In the while loop, the if-statement condition is checked. The character “c” stores the current character at the index pointed by the “len” variable. The “reverseString” stores all the characters of the string but in a reversed manner. The value of the “len” variable is decremented by 1. The loop terminates when the value of len becomes negative:
while(check==true){
if(len>=0)
{
char c=originalString.charAt(len);
reverseString +=c;
len--;
}
else if(len<0)
{
check=false;
}}
A comparison of the original and reverse string is printed:
System.out.println("Original String is : " + "\""+ originalString + "\"");
System.out.println("Reverse String is : " + "\"" + reverseString +"\"");
Complete Code & Output
Method 2: Using Bytes and Reverse Iteration
In Java, the bytes array is used to store the data in the form of bytes at contiguous memory locations. The bytes array can also be used to reverse the strings.
In this method, a string variable “stringExample” is created with the following values. The two-byte arrays are created. The “stringByte” array converts the string into bytes and stores it. The “reverseByte” has the same length as that of the “stringByte” array. An integer variable “j” is declared for reversing and storing the values at specific indexes:
String stringExample = "JavaBeat";
byte[] stringByte=stringExample.getBytes();
byte[ ] reverseByte=new byte[stringByte.length];
int j=0;
The for loop is used to traverse through the byte array elements. The “reverseByte” array stores the string variable by using the reverse iteration. The “j” variable is incremented in each iteration:
for(int i=stringByte.length-1;i>=0;i--)
{
reverseByte[j]=stringByte[i];
j++;
}
System.out.println("Reverse String is " + "\"" + new String(reverseByte) + "\"");
Complete Code & Output
Method 3: Using CharArray
The CharArray or character array in Java is a type of data structure that stores the characters at various indexes in contiguous memory locations. You can also use the CharArray to reverse a String. For this purpose, the string is stored in the form of a character in the CharArray. The CharArray is then printed using the reverse iteration.
By using the following line of code, import the necessary dependencies and classes from the “java.util” package:
import java.util.*;
The string variable “str” is initialized with the following values. The character array “reverseString” stores the string in the form of characters which is returned by the toCharArray(). The for loop traverses the character array’s elements in descending order. Each index of the array is then printed:
String str="Welcome to JavaBeat";
char [ ] reverseString= str.toCharArray();
for(int i=reverseString.length-1;i>=0;i--)
{
System.out.print(reverseString[i]);
}
Complete Code & Output
How to Reverse a String Using Built-in Methods?
Built-in methods are those methods that are provided as default by various classes and libraries in Java. To reverse a string in Java, there are various public classes such as StringBuilder, StringBuffer, ArrayList, etc.
Let’s explore these methods and classes.
Method 1: Using StringBuilder
The StringBuilder class is used to construct mutable strings. Such strings are more efficiently and easily modified by various methods such as append, delete, insert, etc. While implementing the string manipulation functionality, the user can make use of the StringBuilder class to simplify the approach.
In this code, the string variable is declared and initialized. Similarly, the StringBuilder class created “reverseString” object that stores the output:
String originalString="welcome to JavaBeat";
StringBuilder reverseString=new StringBuilder();
The data of the string variable “originalString” are copied to the “reverseString”. The “reverseString” object invokes the reverse() method:
reverseString.append(originalString);
System.out.println("Original String is : " + originalString); //prints original
System.out.println("Reverse of the string is : " + "\"" + reverseString.reverse() +"\""); //prints reverse string
Complete Code & Output
Method 2: Using StringBuffer
In Java, StringBuffer class is a flexible and versatile class for manipulating strings. It enables the developers to change the contents of the strings once created. This functionality makes the StringBuffer flexible and convenient to use for many use cases such as reversing the string.
In this code, a string variable “originalString” is created. The StringBuffer class is used to initialize the “strBuffer” object with the string variable. The StringBuffer object calls the reverse() function to reverse the given string in Java. It modifies the contents of the strings which is then printed:
String originalString="Let's learn Java";
StringBuffer strBuffer=new StringBuffer(originalString);
System.out.println("Reverse string is " + "\"" + strBuffer.reverse() + "\"");
Complete Code & Output
Method 3: Using ArrayList (Built-in)
The ArrayList in Java can dynamically grow and shrink according to the code requirement, unlike the traditional arrays. In Java, the Collections Framework provides the ArrayList class that is used to store multiple elements. To reverse the strings using the ArrayList, use built-in methods:
To use the ArrayList, import the “java.util” package within the code:
import java.util.*;
Inside the main() method, a string variable “originalString” is declared along with an ArrayList “reverseList”:
String originalString="JavaBeat";
List reverseList = new ArrayList<>();
The for loop iterates over the originalString characters that are added to ArrayList “reverseList”. The charAt() method points to the specific character in the originalString variable:
for(int i =0;i<originalString.length();i++)
{
reverseList.add(originalString.charAt(i));
}
The Collection framework from the java.util package invokes the reverse method that accepts reverseList as arguments. The ListIterator object “listIterator” traverses through the elements using the while loop. It continues to execute and print values unless the hasNext() method returns false:
Collections.reverse(reverseList);
ListIterator listIterator = reverseList.listIterator();
while (listIterator.hasNext())
System.out.print(listIterator.next());
Complete Code & Output
How to Reverse a String Using Data Structures?
Data Structures provide an efficient and effective method to access, manipulate, manage, and organize the data. In programming languages, data structures lay the foundations of many complex yet useful algorithms. To reverse the strings in Java, use the Stacks and Deques:
Method 1: Using Stack
Stacks are common and useful data structures that allow the LIFO format. Stacks are the containers to store elements. However, the elements that are stored first in the stack will be removed last. The most common methods to add and remove elements from the stack are push() and pop(). The same method is used for string reversal in Java.
A string variable “str” is created with the given values. The if-statement checks the provided string for empty or null values, and the following message is displayed on the console:
String str="Welcome to JavaBeat";
if(str == null || str.equals(""))
{
System.out.println("The string can't be reversed");
}
The control shifts to the else block if the string is not null and is not initialized with empty spaces. A stack of character data types is created. The character array is created that stores the contents of the string variable. The for loop traverses through the character array and adds each character to the stack via the push() method. The integer variable “j” is initialized with the value “0”.
Furthermore, the while loop continues to execute unless the stack is not empty i.e., isEmpty() method returns false. The Character array is rewritten by popping the elements from the stack and adding them to the respective index of the array. The value of j is incremented and the Character array is printed:
else {
Stack <Character> stack=new Stack<Character>();
char [ ] ch=str.toCharArray();
for(int i=0;i<ch.length;i++)
{
stack.push(ch[i]);
}
int j=0;
while(!stack.isEmpty())
{
ch[j]=stack.pop();
System.out.print(ch[j]);
j++;
}
}
Complete Code & Output
Method 2: Using the Deque
In Java, the deque is a data structure that allows the modification of the elements from both ends i.e., front or rear. It provides flexibility to the code making it useful for many algorithms and use cases (e.g. sliding window problems, palindromes, string reversal, etc).
The string reversal can also be achieved by using the deque. For this purpose, import the ArrayDeque and Deque classes from java.util package:
import java.util.ArrayDeque;
import java.util.Deque;
In this code snippet, a string variable “original” is initialized. The deque of character type is created. Then, the for loop iterates over the character array created from the original variable and returned by the toCharArray(). Finally, each character is then added to the deque:
String original = "Welcome to JavaBeat"; // initialized strings
Deque<Character> deque = new ArrayDeque<>(); //dequeue structures
for (char c : original.toCharArray()) {
deque.addFirst(c);
}
The StringBuilder class creates a “reversingString” object. The while loop adds the deque elements to the “reversingString” using the pollFirst() function. The loop terminates when there are no more elements to traverse and the deque is empty:
StringBuilder reversingString = new StringBuilder(); //Using StringBuilderwhile (!deque.isEmpty()) {
reversingString.append(deque.pollFirst());
}
System.out.println("Reversed String: " + reversingString); // print Strings
Complete Code & Output
How to Reverse a String Using Apache Common Lang?
The StringUtils from ApacheCommonLang provide multiple static methods for trimming, manipulating, checking, and padding the strings. To work with the StringUtils class, provide the given dependency inside the pom.xml or build.gradle file of your Maven or Gradle project:
<dependencies>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
</dependencies>
Inside the main() method, import the StringUtils class from the Apache Common Lang using the following line of code:
import org.apache.commons.lang3.StringUtils;
The string variable “str” is created with the following values. The reverse() method is a built-in static function of the StringUtils class. The “str” variable is passed as an argument to it which is then printed after reversing:
String str="Welcome to JavaBeat";
System.out.println(StringUtils.reverse(str));
Complete Code & Output
How to Reverse a String Using the Recursion?
Recursion refers to the functionality where a function repeatedly calls itself until the specified condition is true. In other terms, the recursive calls are made to the function by the function itself, and the problem is divided into smaller instances for easy solving.
For reversing a string using recursion, use the following code inside the main method.
In this code, a string variable “str” is created that contains the following data. The reverseString() function is only called once by the users and the rest of the recursive calls will be made by the function itself. The function accepts a string as an argument:
String str="Reversing a String using Recursion";
System.out.println(reverseString(str));
In this method, the if-statement checks the strings containing null or empty spaces. The else statement is executed when the string is not empty and null. The substring is created from the second character. The recursive calls to the functions add the character to the result in a reverse manner:
public static String reverseString(String revString)
{
if(revString==null || revString.equals(""))
{
return revString;
}
else
{
return reverseString(revString.substring(1)) + revString.charAt(0);
}
Complete Code & Output
That is all from this guide.
Conclusion
Reversing the string in Java is a crucial skill that is required in data manipulation. To reverse a string in Java, use CharArray, built-in methods, recursion and data structures Apache Common Lang, etc. The choice of implementation depends greatly on multiple factors such as compilation time, performance, accurate results, etc.
Among developers, the StringBuilder approach is preferred as it provides a simple, effective, efficient method and fast retrieval of results. This article is a practical and extensive guide for string reversal in Java.