Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

How to do Reverse String in Java?

Updated on 02 June, 2023

5.73K+ views
8 min read

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:

  1. Using StringBuffer or StringBuilder
  2. Using Reverse Iteration
  3. Using charAt() method
  4. Using ArrayList object
  5. Using Recursion
  6. Convert String to Bytes
  7. Using Stack

Let’s go through each of these methods in detail.

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.

  1. Create a stack without characters.
  2. 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.

  1. 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.

Frequently Asked Questions (FAQs)

1. What is the simplest way to reverse a String in Java?

The simplest way to reverse a String in Java is using the StringBuffer class. It supports a method known as reverse() that reverses the contents of the existing StringBuffer object and returns the output StringBuffer object.

2. What is the Recursive method in Java?

A method that calls itself is called a recursive method in Java. The corresponding process is called recursion.

3. What are the applications of String in Java?

In Java, Strings can be used to detect plagiarism in codes. They can be used for encoding and decoding for safe data transfer from sender to receiver. String applications assist you in retrieving information from anonymous data sources. Moreover, Strings and its algorithms applications provide you with improved Filters to solve the Approximate Suffix-Prefix Overlap Problem.

RELATED PROGRAMS