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.
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.
Get curriculum highlights, career paths, industry insights and accelerate your technology journey.
Download brochure
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:
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
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
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
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
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
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();
List revString = 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
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.
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
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
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
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.
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
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.