Introduction to Reverse String in Java
A string is a character sequence that is an object in Java. Several operations can be performed on the String object in Java. One of the commonly used operations is String Reversal. A String that is reversed is said to be a Reverse String. For example, the ‘HAPPY’ string can be reversed as’ YPPAH’. Similarly, the ‘LUCKY’ string can be written as ‘YKCUL’ when it is reversed.
Table of Content
- Introduction to Reverse String in Java
- Logic Behind Reverse String in Java
- How does it work?
- How to Reverse String in Java using Various Methods?
Logic Behind Reverse String in Java
There are several ways in which a string can be reversed. For each of the methods, separate functions and loops will be used. Even though the methods are different, the underlying process behind the reversal of string is almost similar, and it is mentioned below:
- Input a string either in code or using user input.
- Take the characters of the string starting from the last position and store them in any variable.
- Display the final output.
How does it work?
We can achieve the string reverse in Java using StringBuilder.
We can create an object of the StringBuilder and use the string.reverse() function for the string reverse. Since this is a string function, you need not import any additional library. In the same way, we can use the StringBuffer reverse method to get the reverse of any specified string. Also, we can use our own custom code to get the job done. We need to get the string and loop length through the last index to 0 to get each character one by one.
Syntax
public StringBuilder reverse();
Using the StringBuilder, we can create an object of this class and use the function reverse() to get the reverse of any string.
StringBuilder sb=new StringBuilder(str);
sb.reverse();
public StringBuffer reverse();
Using the StringBuffer, we can create an object of this class and use the function reverse() to get the reverse of any string.
StringBuffer sb=new StringBuffer (str);
sb.reverse();
We can see everything is similar to StringBuffer and StringBuilder.
Using the charAt() function to read character by character from the last index to the o index.
How to Reverse String in Java using Various Methods?
There are several methods in order to perform the reversal of string. Let us look into each of them in detail.
Example #1 – Using StringBuffer or StringBuilder
Code:
//Java program to Reverse a String using StringBuffer
//class
public class ReverseStringExample{
//main method
public static void main(String[] args) {
//string
String str1 = "Annamu";
//reversed string will be stored in rev variable
String rev = new StringBuffer(str1).reverse().toString();
//print string before reverse
System.out.println("\nString before reversal : "+str1);
//print string after reverse
System.out.println("String after reversal : "+rev);
}
}
Output:
Here, the input string undergoes buffering using the StringBuffer, and the reversal is achieved through the reverse() method. After reversing the buffer, it converts to a string using the toString() method.
Similarly, StringBuilder can also be used instead of StringBuffer, which is explained in the below program.
Java Program to Reverse a String using StringBuilder.
Code:
//class
public class ReverseStringExample{
//main method
public static void main(String[] args) {
//string
String str1 = "Annamu";
//reversed string will be stored in rev variable
String rev = new StringBuilder(str1).reverse().toString();
//print string before reverse
System.out.println("\nString before reversal : "+str1);
//print string after reverse
System.out.println("String after reversal : "+rev);
}
}
Output:
Here also, it can be seen that the string is reversed even though StringBuilder is used.
Example #2 – Using charAt() method
Code:
//class
public class ReverseStringExample{
//main method
public static void main(String[] args) {
//string
String str1 = "Java Programming";
//reversed string will be stored in reverseS variable
String reverseS = "";
//length of string will be stored in len
int len=str1.length();
for(int i=len-1;i>=0;i--)
reverseS = reverseS + str1.charAt(i);
//print string before reverse
System.out.println("\nString before reversal : "+str1);
//print string after reverse
System.out.println("String after reversal : "+ reverseS);
}
}
Output:
This program uses a for loop to store characters from the input string in the variable reverseS, starting from the last position. After storing all the characters, it displays the reversed string.
Example # 3 – Using ArrayList object
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
//class
public class ReverseStringExample{
//main method
public static void main(String[] args) {
//string
String str1 = "Programming Language";
//conversion of input string to character array
char ch[]=str1.toCharArray();
//add character array to object of the ArrayList
List<Character> obj = new ArrayList<>();
for (char c: ch)
obj.add(c);
//pass the object of arraylist to collections
Collections.reverse(obj);
//create objecct of listiterator to iterate on list
ListIterator objli = obj.listIterator();
//print string before reversal
System.out.println("\nString before reversal : "+ str1);
System.out.println("\nString after reversal : ");
while (objli.hasNext())
System.out.print(objli.next());
}
}
Output:
This program stores characters from the input string in an ArrayList. It reverses the order of the characters using the reverse() method from the Collections class. Following the reversal, an iterator is used to iterate over the list and print the reversed string.
Example #4 – Using Reversive Iteration
Code:
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.ListIterator;
//class
public class ReverseStringExample{
//main method
public static void main(String[] args) {
//string
String str1 = "Hello World";
//conversion of input string to character array
char ch[]=str1.toCharArray();
//reversed string will be stored in reverseS variable
String reverseS = "";
//For loop for reversal of a string
for(int i=ch.length-1;i>=0;i--)
{
reverseS+=ch[i];
}
//print string before reversal
System.out.println("\nString before reversal : "+ str1);
System.out.println("\nString after reversal : " +reverseS);
}
}
Output:
In this program, the for loop will store characters of the input string in the variable reverseS, beginning from the last position. After storing all the characters, the program will display the reversed string.
Example #5 – Using Recursion
Code:
//class
public class ReverseStringExample{
//function reversal
String rev(String str1) {
//if length of the string is zero, return null
if(str1.length() == 0)
{
return " ";
}
//else return the character obtained on following method
return str1.charAt(str1.length()-1) + rev(str1.substring(0,str1.length()-1));
}
public static void main(String[ ] args)
{
// create object of class
ReverseStringExample r=new ReverseStringExample();
//input string
String str1 = "Java Program";
//print string before reversal
System.out.println("\nString before reversal : "+ str1);
//print string after reversal
System.out.println("\nString after reversal : " + r.rev(str1));
}
Output:
This program creates a recursive function that checks the length of a string and reverses it accordingly.
Conclusion
Various methods exist in Java for reversing a string, including using a StringBuilder or converting the string to a character array. The StringBuilder approach is efficient as it allows for in-place modification. Choosing the appropriate method depends on the specific requirements and performance considerations of the task at hand.
FAQ’s
Q1. How do I handle null or empty strings when reversing in Java?
Answer: You should add appropriate checks for null or empty strings before attempting to reverse to avoid unexpected behavior or exceptions.
Q2. How does reversing a string relate to palindrome checking in Java?
Answer: Reversing a string is often used in palindrome-checking algorithms. Checking if a string is equal to its reverse can determine if it’s a palindrome.
Q3. What is the time complexity of reversing a string using different methods?
Answer: Reversing a string using StringBuilder or manually with a character array has a time complexity of O(n), where n is the length of the string. The Java 8+ Stream approach has a similar time complexity.
Q4. How do I handle null or empty strings when reversing in Java?
Answer: You should add appropriate checks for null or empty strings before attempting to reverse to avoid unexpected behavior or exceptions.
Q5. Can I reverse only a portion of a string in Java?
Answer: Yes, you can use the substring method to extract a portion of the string, reverse it, and then concatenate it back with the remaining parts.
Recommended Articles
We hope that this EDUCBA information on “Reverse String in Java” was beneficial to you. You can view EDUCBA’s recommended articles for more information.