Reverse a String in Java with Example

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

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:
  1. What is the reverse of a string in Java?
  2. Different ways to reverse a string in Java 
  3. Methods to use the StringBuilder class to reverse a string
  4. Conclusion
  5. FAQs

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.

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:

Reverse a String in Java with Example

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:

 

String 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

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:

 

tring 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:

 

rogram 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

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:

rogram 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?

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:

 

String 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:

 

rogram 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

Check out: Polymorphism in Java

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:

eroVired; 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:

 

eroVired; 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

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:

 

eroVired; 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:

 

eroVired; 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

Reverse a String in Java with Example

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

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
r = "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
r = "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
atic 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
r = "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
r = "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.

FAQs
If you reverse a string in Java, you flip its order and make it read backward. It is useful for debugging or writing a loop in an alternate way.
You can use different methods to reverse a string in Java, including the reverse iteration method and the CharAt method.
Using the StringBuilder or StringBuffer is the most common way of reversing a string in Java.

Book a free counselling session

India_flag

Get a personalized career roadmap

Get tailored program recommendations

Explore industry trends and job opportunities

left dot patternright dot pattern

Programs tailored for your Success

Popular

Data Science

Technology

Finance

Management

Future Tech

Upskill with expert articles
View all
Hero Vired logo
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.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved