Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconSoftware Development USbreadcumb forward arrow iconHow to do Reverse String in Java?

How to do Reverse String in Java?

Last updated:
5th Jan, 2023
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
How to do Reverse String in Java?

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.

Ads of upGrad blog

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.

  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.
Ads of upGrad blog

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.

Profile

Pavan Vadapalli

Blog Author
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working on solving problems of scale and long term technology strategy.
Get Free Consultation

Select Coursecaret down icon
Selectcaret down icon
By clicking 'Submit' you Agree to  
UpGrad's Terms & Conditions

Our Best Software Development Course

Frequently Asked Questions (FAQs)

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

2What is the Recursive method in Java?

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

3What 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.

Explore Free Courses

Suggested Blogs

Top 19 Java 8 Interview Questions (2023)
6009
Java 8: What Is It? Let’s conduct a quick refresher and define what Java 8 is before we go into the questions. To increase the efficiency with
Read More

by Pavan Vadapalli

27 Feb 2024

Top 10 DJango Project Ideas &#038; Topics
12448
What is the Django Project? Django is a popular Python-based, free, and open-source web framework. It follows an MTV (model–template–views) pattern i
Read More

by Pavan Vadapalli

29 Nov 2023

Most Asked AWS Interview Questions &#038; Answers [For Freshers &#038; Experienced]
5648
The fast-moving world laced with technology has created a convenient environment for companies to provide better services to their clients. Cloud comp
Read More

by upGrad

07 Sep 2023

22 Must-Know Agile Methodology Interview Questions &#038; Answers in US [2024]
5385
Agile methodology interview questions can sometimes be challenging to solve. Studying and preparing well is the most vital factor to ace an interview
Read More

by Pavan Vadapalli

13 Apr 2023

12 Interesting Computer Science Project Ideas &#038; Topics For Beginners [US 2023]
10722
Computer science is an ever-evolving field with various topics and project ideas for computer science. It can be quite overwhelming, especially for be
Read More

by Pavan Vadapalli

23 Mar 2023

Begin your Crypto Currency Journey from the Scratch
5456
Cryptocurrency is the emerging form of virtual currency, which is undoubtedly also the talk of the hour, perceiving the massive amount of attention it
Read More

by Pavan Vadapalli

23 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5551
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Complete SQL Tutorial for Beginners in 2024
5033
SQL (Structured Query Language) has been around for decades and is a powerful language used to manage and manipulate data. If you’ve wanted to learn S
Read More

by Pavan Vadapalli

22 Mar 2023

Top 10 Cyber Security Books to Read to Improve Your Skills
5521
The field of cyber security is evolving at a rapid pace, giving birth to exceptional opportunities across the field. While this has its perks, on the
Read More

by Keerthi Shivakumar

21 Mar 2023

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon