A string is a character sequence and is treated as an object in Java. It is an object in Java that stores the data in a character array. A string that is reversed is called a reverse string. For example, the reverse of the ‘program’ string is ‘margorP’.
The logic behind string reversal in Java:
Various ways are available to reverse a string, with each using separate functions. Although the methods used are different, the fundamental process behind the reversal of string is nearly the same. The typical logic used is:
- Input a string using user input or in code.
- Take the characters of the string beginning from the last position and save them in any variable.
- Display the output.
Learn Software Development Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs or Masters Programs to fast-track your career.
Various methods to reverse the string in Java:
- Using StringBuffer or StringBuilder
- Using Reverse Iteration
- Using charAt() method
- Using ArrayList object
- Using Recursion
- Convert String to Bytes
- Using Stack
Let’s go through each of these methods in detail.
Popular Courses & Articles on Software Engineering
1. By StringBuilder / StringBuffer
StringBuffer or StringBuilder class has a built-in method reverse() that reverses the characters in the string. It substitutes the characters’ sequence in reverse order. This method is the static method that implements the logic to reverse string in java.
The StringBuffer and StringBuilder are two utility classes in Java that manage resource allocation of string manipulations.
Using StringBuffer: Java Program that reverses a string using StringBuffer: public class ExampleofReverseString{ public static void main(String[] args) { String str1 = "Apple"; //stores reversed string order in the rev variable String rev = new StringBuffer(str1).reverse().toString(); //prints the string before reverse System.out.println("\The string before reversal is: "+str1); //prints the string after reverse System.out.println("The string after reversal is: "+rev); } } Output: The string before reversal is: Apple The string after reversal is: elppA
In the above example, the string that is provided as input would be buffered using the StringBuffer. It would then be reversed using the reverse() method. After the buffer is reversed, it would be converted to a string using the toString() method.
Using StringBuilder: StringBuilder class is highly preferred compared to StringBuffer class. It is faster and not synchronized. Java Program that reverses a string using StringBuilder: public class ExampleofReverseString{ public static void main(String[] args) { String str1 = "School"; //stores reversed string in rev variable String rev = new StringBuilder(str1).reverse().toString(); //prints the string before reverse System.out.println("\nString before reversing: "+str1); //prints the string after reverse System.out.println("String after reversing: "+rev); } } Output: String before reversing: School String before reversing: loohcS
In the above code, the object for the StringBuilder class is used. The corresponding StringBuilder objects are memory efficient, mutable, and fast in execution. The object calls the built-in reverse() method to provide the desired output.
2. By Reverse Iteration
Java Program that reverses a string using Reverse Iteration:
public class StringReversal { public static String reverseString(String st){ char ch[]=st.toCharArray(); String rev=""; for(int i=ch.length-1;i>=0;i--) { rev+=ch[i]; } return rev; } } public class TestStringReversal { public static void main(String[] args) { System.out.println(StringReversal.reverseString("I am teacher ")); System.out.println(StringReversal.reverseString("I teach English subject")); } } Output: I ma rehcaet I hcaet hsilgnE tcejbus
In the above program for the reverse string in java, the characters of the input string are stored in the rev+ variable beginning from the last position using for loop. The reversed string will be shown in the output after all the characters are stored.
You can use While Loop for Reverse Iteration, and its code is as below:
public class StringReversal { public static void main(String[] args) { String stringInput = "This String"; int StrLength=stringInput.length(); while(StrLength >0) { System.out.print(stringInput.charAt(StrLength -1)); StrLength--; } } } Output: gnirtS sihT
3. Using charAt() method
Its Java Program is as below:
public class ExampleofReverseString { public static void main(String[] args) { String str = "Learn Java"; //stores reversed string in revv variable String revv = ""; //length of the string will be stored in len int len=str.length(); for(int i=len-1;i>=0;i--) revv = revv + str.charAt(i); //prints the string before reverse System.out.println("\nString before reversal operation: "+str); //prints the string after reverse System.out.println("String after reversal: "+ revv); } } Output: String before reversal operation: Learn Java String before reversal operation: avaJ nraeL
In this java program to reverse a string, the input string characters are stored in the revv variable beginning from the last position using for loop. After all the characters are stored, the reversed string will be reflected in the output.
4. Using ArrayList object
Its Java Program is as below:
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.ListIterator; public class ExampleofReverseString { public static void main(String[] args) { String str = "Enjoy coding"; //converts input string to a character array char ch[]=str.toCharArray(); //adds character array to object of the ArrayList List<Character> obj = new ArrayList<>(); for (char c: ch) obj.add(c); //passes the object of ArrayList to collections Collections.reverse(obj); //creates object of listiterator to repeat on list ListIterator objnew = obj.listIterator(); //prints the string before reversal System.out.println("\nString before reversal operation: "+ str); //prints the string after reversal System.out.println("\nString after reversal operation: "); while (objnew.hasNext()) System.out.print(objnew.next()); } } Output: String before reversal operation: Enjoy coding String after reversal operation: gnidoc yojnE
This java program to reverse a string stores the input string’s characters in the ArrayList object. It is reversed using the reverse () method in the collections. The iterator iterates across the list and prints the reversed string after it is reversed.
5. Using Recursion
Its Java Program is as below:
public class ExampleofReverseString { // defines reversal function String revs(String str) { // returns null if the length of the string is zero if(str.length() == 0) { return " "; } //otherwise returns the character resultant from the following method return str.charAt(str.length()-1) + revs(str.substring(0,str.length()-1)); } public static void main(String[ ] args) { // creates an object of class ExampleofReverseString r = new ExampleofReverseString (); //inputs string String str = "Master in Java"; //prints the string before reversal System.out.println("\nString before reversal operation: "+ str); //prints the string after reversal System.out.println("\nString after reversal operation: " + r.revs(str)); } Output: String before reversal operation: Master in Java String after reversal operation: avaJ ni retsaM
A recursive function is generated in this Java program. It checks the string’s length and ten reverses. It works identically to reverse function in java.
6. By Conversion of a String to Bytes
It uses the getBytes() method that converts or splits the input string into bytes. At that moment, the byte array length equals the length of the input string. The program then gets the bytes in reverse order and saves them in a new byte array.
In the following code, a byte array is temporarily generated. Two-byte arrays are created -one to store the converted bytes and another to save the result in reverse order.
Its Java Program is as below:
public static void main(String[] arg) { String inputvalue = "Computer"; byte[] strByteArray = inputvalue.getBytes(); byte[] result = new byte[strByteArray.length]; // Stores result in reverse order in the result byte[] for (int i = 0; i < strByteArray.length; i++) result[i] = strByteArray [strByteArray.length - i - 1]; System.out.println( "String after reverse operation is:" +new String(result)); } Output: String after the reverse operation is: retupmoC
7) Using Stack
This method involves the following steps to reverse a Java string using the Stack data structure.
- Create a stack without characters.
- Transform an input string into a character array using the String.toCharArray() method. Subsequently, it adds each character to the stack.
iii. Retrieve characters from the stack until it’s empty and then again assign the characters into a character array. So, now the characters will arrive in reverse order.
- The character array is converted into a string using String.copyValueOf(char[]) and finally returns the new string.
Its Java Program is as below:
import java.util.Stack; class Main { public static String reverse(String str) { // checks whether the string is empty or null if (str == null || str.equals("")) { return str; } // generates an empty stack of characters Stack<Character> stack = new Stack<Character>(); // adds all characters of the input string into the stack char[] ch = str.toCharArray(); for (int i = 0; i < str.length(); i++) { stack.push(ch[i]); } // begins from index 0 int m = 0; // retrieves characters from the stack until it gets empty while (!stack.isEmpty()) { // assigns each retrieved character back to the character array ch[m++] = stack.pop(); } // transforms the character array into a string and returns it return String.copyValueOf(ch); } public static void main(String[] args) { String str = "Technology Innovation"; str = reverse(str); System.out.println("The reverse of the input string: " + str); } } Output The reverse of the input string: ygolonhceT noitavonnI Get Started With Your Java Journey with UpGrad
If you want to learn Java, you must understand Core Java concepts. For that, you can pursue UpGrad’s Master of Science in Computer Science. It covers topics like Core Java, OOPS concepts, objects, and classes in Java, Methods in Java, Java Virtual Machine, Polymorphism, Inheritance, Abstraction, Encapsulation, etc. You will get industry expert guidance. These experts conduct interactive live sessions that cover curriculum and advanced topics.