
Java is one of the most versatile object-oriented programming languages. Java is platform-independent and contains different in-built data structures. Strings are widely preferred data structured by Java developers. Reversing is one of the primary functions performed on Java strings. Therefore, explore the different methods to reverse a string in Java in this article.Â
Table of Content: |
H2: What is the Reverse of a String in Java?
When you reverse a string in Java, it will change the order of a given string. The change will ensure that the last character of the Java string becomes the first one. Additionally, a Java program to reverse a string also enables you to check the Palindrome of the given string. Let’s deep dive and discusses different ways to reverse a string in Java with examples.
Enroll in a Full Stack Development course.
H2: Different Ways to Reverse a String in Java
If you are wondering how to reverse a string in Java, you can check out a few methods below:
H2: Use the StringBuilder Class to Reverse a String in Java
The StringBuilder Java program to reverse a string is mutable and memory efficient. They can also be executed faster than any other Java program to reverse a string. Â The code below will help you understand how to reverse a java string using stringbuilder.
Syntax:
//ReverseString using StringBuilder. public static void main(String[] arg) { // declaring variable String input = "Independent"; // creating StringBuilder object StringBuilder stringBuildervarible = new StringBuilder(); // append a string into StringBuilder stringBuildervarible //append is inbuilt method to append the data stringBuildervarible.append(input); // reverse is inbuilt method in StringBuilder to use reverse the string stringBuildervarible.reverse(); // print reversed String System.out.println( "Reversed String : " +stringBuildervarible); } Output: Reversed String : tnednepednI
Read: Mastering Constructors in Java: Types and Examples
H3: By using toCharArray()
The toCharArray() method to reverse a string in Java uses the total length of the string variable. The for loop iterates up to the end of the string index zero. This approach to reverse a string in Java can employ the in-built reverse() method to receive your intended output. The code below will help you understand how to reverse a java string using tochartarray.
Syntax:
/ReverseString using CharcterArray. public static void main(String[] arg) { // declaring variable String stringinput = "Independent"; // convert String to character array // by using toCharArray char[] resultarray = stringinput.toCharArray(); //iteration for (int i = resultarray.length - 1; i >= 0; i--) // print reversed String System.out.print(resultarray[i]); } Output: tnendnepednI
H3: By Using While Loop
A simple way to reverse a string in Java is using the while loop. You can move your cursor to get the string length or iterate via the string index and get rid of the loop. The code below will help you understand how to reverse a java string using while loop.
Syntax:
// Java program to reverse a string using While loop import java.lang.*; import java.io.*; import java.util.*; public class strReverse { public static void main(String[] args) { String stringInput = "My String Output"; //Get the String length int iStrLength=stringInput.length(); //Using While loop while(iStrLength >0) { System.out.print(stringInput.charAt(iStrLength -1)); iStrLength--; } } } Output: tuptuO gnirtS yM
Learn: What is Inheritance in Java – A Complete Guide
H3: By Using for Loop
The for loop to reverse a string in Java prints the string character in place of the index (i-1). The for loop Java program to reverse a string begins and iterates the string length to reach index 0. Â The code below will help you understand how to reverse a java string using loop.
Syntax:
// Java program to reverse a string using For loop import java.lang.*; import java.io.*; import java.util.*; public class strReverse { public static void main(String[] args) { String stringInput = "My New String"; //Get the String length int iStrLength=stringInput.length(); //Using For loop for(iStrLength=stringInput.length();iStrLength >0;-- iStrLength) { System.out.print(stringInput.charAt(iStrLength -1)); } } } Output: gnirtS weN yM
Explore: What is Palindrome in Java?
H3: By Converting String to Bytes
The getBytes() approach to reverse a string in Java will convert a specific string into bytes. The length of the temporary byte array will be equal to the string length. The code below will help you understand how to reverse a java string using Bytes.
Syntax:
//ReverseString using ByteArray. public static void main(String[] arg) { // declaring variable String inputvalue = "Independent"; // getBytes() is inbuilt method to convert string // into bytes[]. byte[] strAsByteArray = inputvalue.getBytes(); byte[] resultoutput = new byte[strAsByteArray.length]; // Store result in reverse order into the // result byte[] for (int i = 0; i < strAsByteArray.length; i++) resultoutput[i] = strAsByteArray[strAsByteArray.length - i - 1]; System.out.println( "Reversed String : " +new String(resultoutput)); } Output: Reversed String : tnednepednI
H3: By Using Array List Objects
You can convert any Java input string into a character array. After that, you will have to include the array's characters inside the ArrayList object. The code below will help you understand how to reverse a java string using list object.
Syntax:
// Java program to Reverse a String using ListIterator import java.lang.*; import java.io.*; import java.util.*; // Class of ReverseString class ReverseString { public static void main(String[] args) { String input = "Reverse a String"; char[] str = input.toCharArray(); ListrevString = new ArrayList<>(); for (char c : str) revString.add(c); Collections.reverse(revString); ListIterator li = revString.listIterator(); while (li.hasNext()) System.out.print(li.next()); } } Output: gnirtS a esreveR
Check out: Polymorphism in Java
H3: By Using StringBuffer
If you are wondering how to reverse string in Java, you can always use the StringBuffer method. The StringBuffer method works quite similarly to the StringBuilder reverse method in Java. The code below will help you understand how to reverse a java string using stringbuffer.
Syntax:
package HeroVired; import java.util.*; public class StringRev{ // Function to reverse a string in Java using StringBuffer public static String rev(String s){ return new StringBufferr(s).reverse().toString(); } public static void main(String[] args){ String s= "Welcome to HeroVired"; // Note that string is immutable in Java s= rev(s); System.out.println("Result after reversing a string is : "+s); } } Output: StringBuffer sb =new StringBuffer("JavaHeroVired"); System.out.println(sb.reverse()); Output: deriVoreHavaJ
Usually, the StringBuilder approach is preferred more than the StringBuffer approach to reverse a string in Java.Â
H3: By Using Recursion
The recursion method involves the function calling itself. Once you write a method using this approach, it will reverse a string in Java by calling itself recursively. The code below will help you understand how to reverse a java string using recursion.
Syntax:
package HeroVired; import java.util.*; public class StringRecursion{ String rev(String str) { if(str.length() == 0) return" "; return str.charAt(str.length()-1) + rev(str.substring(0,str.length()-1)); } public static void main(String[ ] args) { StringRecursion r=new StringRecursion(); Scanner sc=new Scanner(System.in); System.out.print("Enter the string : "); String s=sc.nextLine(); System.out.println("Reversed String: "+r.rev(s)); } } Output: Enter the string : Java is the blooming technology since its existence Reversed String: ecnetsixe sti ecnis ygolonhcet gnimoolb eht si avaJ
Find out: Ternary Operator in Java
H3: By Using Reverse Iteration
Before using the reverse iteration method, you will have to transform the given String to Character Array with the help of the CharArray() method. After that, you will be able to iterate it using the reverse method in Java. The code below will help you understand how to reverse a java string using reverse iteration.
Syntax:
package HeroVired; import java.util.*; public class StringRev{ // Function to reverse a string in Java public static String reverseString(String s){ //Converting the string into a character array char c[]=s.toCharArray(); String reverse=""; //For loop to reverse a string for(int i=c.length-1;i>=0;i--){ reverse+=c[i]; } return reverse; } public static void main(String[] args) { System.out.println(reverseString("Hi All")); System.out.println(reverseString("Welcome to HeroVired Blog")); } } Output: llA iH golB deriVoreH ot emocleW
H3: By Using CharAt Method
The CharAt Java program to reverse a string involves extracting the characters from the input String. The primary purpose of the ChartAt() Java program to reverse a string is to deliver the character at the specified index in the provided String. It is one of the simplest approaches to reverse a string in Java. The code below will help you understand how to reverse a java string using chart method.
Syntax:
package HeroVired; import java.util.*; public class StringReverse{ public static void main(String args[]) { String initial, rev=""; Scanner in=new Scanner(System.in); System.out.println("Enter the string to reverse"); initial=in.nextLine(); int length=initial.length(); for(int i=length-1;i>=0;i--) rev=rev+initial.charAt(i); System.out.println("Reversed string: "+rev); } } Output: Enter the string to reverse HELLO HEROVIRED Reversed string: DERIVOREH OLLEH
H2: Conclusion
Learn about the different ways to reverse a string in Java to perform the function easily. You can start with the more basic Java program to reverse a string before moving ahead to the complicated ones.Â
H2: Comparison of different methods to Reverse a String in Java
Here's a comparison overview of different methods to reverse a string in Java:
Method | Description | Code Example |
Using StringBuilder | Converts the string into a StringBuilder and calls reverse() method |
String str = "Hello World"; StringBuilder sb = new StringBuilder(str); sb.reverse(); String reversedStr = sb.toString(); |
Using char Array | Converts the string into a character array and reverses it by swapping characters |
String str = "Hello World"; char[] charArray = str.toCharArray(); int left = 0; int right = charArray.length - 1; while (left < right) { char temp = charArray[left]; charArray[left] = charArray[right]; charArray[right] = temp; left++; right--; } String reversedStr = new String(charArray); |
Using recursion | Recursively reverses the string by swapping characters |
public static String reverseString(String str) { if (str.isEmpty()) { return str; } else { return reverseString(str.substring(1)) + str.charAt(0); } } String reversedStr = reverseString("Hello World"); |
Using StringBuilder and built-in reverse method | Uses the reverse() method of the StringBuilder class to directly reverse the string |
String str = "Hello World"; StringBuilder sb = new StringBuilder(str).reverse(); String reversedStr = sb.toString(); |
Using Java 8 Stream API | Converts the string into a stream of characters, reverses the order, and joins them back into a string |
String str = "Hello World"; String reversedStr = new StringBuilder(str).chars().mapToObj(c -> (char) c).collect(Collectors.collectingAndThen(Collectors.toList(), list -> { Collections.reverse(list); return list.stream().map(Object::toString).collect(Collectors.joining()); })); |
The time and space complexities mentioned here are general estimations and can vary depending on the specific implementation.