A string is a sequence of characters that behave like an object in Java. The string is one of the most common and used data structures after arrays. It is an object that stores the data in a character array.

For better clarity, just consider a string as a character array wherein you can solve many string-based problems.

To create a string object, you need the java.lang.String class. Java programming uses UTF -16 to represent a string. Strings are immutable so that their internal state remains constant after the object is entirely created. The string object performs various operations, but reverse strings in Java are the most widely used function.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Reverse in Java

Example: HELLO string reverse and give the output as OLLEH

How to Reverse a String in Java?

Since the strings are immutable objects, you need to create another string to reverse them. The string class doesn't have a reverse method to reverse the string. It has a toCharArray() method to do the reverse.

By Using toCharArray()

The code below will help you understand how to reverse a string. By using toCharArray() method is one approach to reverse a string in Java.

The code also uses the length, which gives the total length of the string variable.

The for loop iterates till the end of the string index zero.

Code 

//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

ReverseAStringInJava_1

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

By Using StringBuilder

Let us see how to reverse a string using the StringBuilder class. StringBuilder or StringBuffer class has an in-build method reverse() to reverse the characters in the string. This method replaces the sequence of the characters in reverse order. The reverse method is the static method that has the logic to reverse a string in Java.

In the code mentioned below, the object for the StringBuilder class is used. 

The StringBuilder objects are mutable, memory efficient, and quick in execution. But it also considers these objects as not thread-safe.

The object calls the in-built reverse() method to get your desired output.

This is a preferred method and commonly used to reverse a string in Java.

Code:

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

ReverseAStringInJava_2

Alternatively, you can also use the StringBuffer class reverse() method similar to the StringBuilder. Both the StringBuilder class and StringBuffer class, work in the same way to reverse a string in Java. Considering reverse, both have the same kind of approach. Although, StringBuilder class is majorly appreciated and preferred when compared to StringBuffer class. The StringBuilder class is faster and not synchronized. These StringBuilder and StringBuffer classes create a mutable sequence of characters. To achieve the desired output, the reverse() method will help you. 

In Java, it will create new string objects when you handle string manipulation since the String class is immutable. The StringBuilder and StringBuffer classes are two utility classes in java that handle resource sharing of string manipulations. 

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

By Using While Loop or For Loop

Simply handle the string within the while loop or the for loop. Get the length of the string with the help of a cursor move or iterate through the index of the string and terminate the loop.

The loop prints the character of the string where the index (i-1).

The loop starts and iterates the length of the string and reaches index 0.

Code Using While Loop

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

ReverseAStringInJava_3

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Code Using For Loop

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

ReverseAStringInJava_4

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

By Converting a String to Bytes

The getBytes() method will split or convert the given string into bytes. The temporary byte array length will be equal to the length of the given string. Get the bytes in reverse order and store them in another byte array.

In the code below, a byte array is temporarily created to handle the string. The getBytes() is also an in-built method to convert the string into bytes. There are two byte arrays created, one to store the converted bytes and the other to store the result in the reverse order.

 Code

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

ReverseAStringInJava_5.

Master Core Java 8 Concepts, Java Servlet & More!

Java Certification TrainingENROLL NOW
Master Core Java 8 Concepts, Java Servlet & More!

By Using ArrayList Object

Using the built-in method toCharArray(), convert the input string into a character array. Then, in the ArrayList object, add the array's characters. The Collections class in Java also has a built-in reverse() function. Since the reverse() method of the Collections class takes a list object, use the ArrayList object, which is a list of characters, to reverse the list.

Copy the String contents to an ArrayList object in the code below. Then, using the listIterator() method on the ArrayList object, construct a ListIterator object. To iterate over the array, use the ListIterator object. It also helps iterate through the reversed list and printing each object to the output screen one-by-one.

Also Read: What is Java API, its Advantages and Need for it

Code

// 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<Character> 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: 

ReverseAStringInJava_6

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

By Using StringBuffer

The String class requires a reverse() function, hence first convert the input string to a StringBuffer, using the StringBuffer method. Then use the reverse() method to reverse the string.

Code

// Java program to convert String to StringBuffer and reverse of string

import java.lang.*;

import java.io.*;

import java.util.*;

public class strReverse {

    public static void main(String[] args)

    {

        String str = "String";

        // conversion from String object to StringBuffer

        StringBuffer sbfr = new StringBuffer(str);

        // To reverse the string

        sbfr.reverse();

        System.out.println(sbfr);

    }

}

Output: 

ReverseAStringInJava_7

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Using Stack

You can use the Stack data structure to reverse a Java string using these steps:

  1. Create a stack that’s empty of characters.
  2. Convert a given string into a character array by using the String.toCharArray() method, then push each character into the stack.
  3. Take characters out of the stack until it’s empty, then assign the characters back into a character array. The characters will enter in reverse order.
  4. Then convert the character array into a string by using String.copyValueOf(char[]) and then return the formed string.

Code

import java.util.Stack;

class Main

{

    // Method to reverse a string in Java using a stack and character array

    public static String reverse(String str)

    {

        // base case: if the string is null or empty

        if (str == null || str.equals("")) {

            return str;

        }

        // create an empty stack of characters

        Stack<Character> stack = new Stack<Character>(); 

        // push every character of the given string into the stack

        char[] ch = str.toCharArray();

        for (int i = 0; i < str.length(); i++) {

            stack.push(ch[i]);

        }

        // start from index 0

        int k = 0; 

        // pop characters from the stack until it is empty

        while (!stack.isEmpty())

        {

            // assign each popped character back to the character array

            ch[k++] = stack.pop();

        }

        // convert the character array into a string and return it

        return String.copyValueOf(ch);

    }

    public static void main(String[] args)

    {

        String str = "Techie Delight";

        str = reverse(str);        // string is immutable

        System.out.println("The reverse of the given string is: " + str);

    }

}

Output

Java_Reverse_string

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Using Character Array

String is immutable in Java, which is why we can’t make any changes in the string object. However, we can use a character array:

  1. Make a character array that’s the same size of the string.
  2. Fill the character array backward using the characters of the string.
  3. Convert the character array into string with String.copyValueOf(char[]) then return it.

Code

class Main

{

    // Method to reverse a string in Java using a character array

    public static String reverse(String str)

    {

        // return if the string is null or empty

        if (str == null || str.equals("")) {

            return str;

        }

        // get string length

        int n = str.length();

        // create a character array of the same size as that of string

        char[] temp = new char[n];

        // fill character array backward with characters in the string

        for (int i = 0; i < n; i++) {

            temp[n - i - 1] = str.charAt(i);

        }

       // convert character array to string and return it

        return String.copyValueOf(temp);

    }

    public static void main(String[] args)

    {

        String str = "Techie Delight";

        // String is immutable

        str = reverse(str);

        System.out.println("The reverse of the given string is: " + str);

    }

}

Output

Java_Reverse_string

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Using Recursion

Here, learn how to reverse a Java string by using the stack data structure. We can effortlessly convert the code, since the stack is involved, by using the recursion call stack. Because string is immutable, we must first convert the string into a character array. Once we’ve done this, we reverse the character array and wrap things up by converting the character array into a string again.

Also Read: 40+ Resources to Help You Learn Java Online

Code

class Main

{

    static int i = 0;

    // Recursive method to reverse a string in Java using a static variable

    private static void reverse(char[] str, int k)

    {

        // if the end of the string is reached

        if (k == str.length) {

            return;

        } 

        // recur for the next character

        reverse(str, k + 1); 

        if (i <= k)

        {

            char temp = str[k];

            str[k] = str[i];

            str[i++] = temp;

        }

    }

    public static String reverse(String str)

    {

        // base case: if the string is null or empty

        if (str == null || str.equals("")) {

            return str;

        }

        // convert string into a character array

        char[] A = str.toCharArray(); 

        // reverse character array

        reverse(A, 0);

        // convert character array into the string

        return String.copyValueOf(A);

    } 

    public static void main(String[] args)

    {

        String str = "Techie Delight";

        // string is immutable

        str = reverse(str);

        System.out.println("The reverse of the given string is: " + str);

    }

}

Output

Java_Reverse_string

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Using Substring() Method

Programmers can use the String.substring(int, int) method to recursively reverse a Java string. Here is one approach:

Code

class Main

{

    // Method to reverse a string in Java using recursion

    private static String reverse(String str)

    {

        // base case: if the string is null or empty

        if (str == null || str.equals("")) {

            return str;

        }

        // last character + recur for the remaining string

        return str.charAt(str.length() - 1) +

                reverse(str.substring(0, str.length() - 1));

    }

    public static void main(String[] args)

    {

        String str = "Techie Delight";

        // string is immutable

        str = reverse(str);

        System.out.println("The reverse of the given string is: " + str);

    }

}

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Using the Character Array and swap() Method

Here’s an efficient way to use character arrays to reverse a Java string.

  1.   First, create your character array and initialize it with characters of the string in question by using String.toCharArray().
  2.       Starting from the two endpoints “1” and “h,” run the loop until they intersect. In the iteration of each loop, swap the values present at indexes “l” and “h.” Increment “l” and decrement “h.”
  3.       Wrap things up by converting your character array into string with String.copyValueOf(char[])then return.

Code

class Main

{

    // Method to reverse a string in Java using a character array

    public static String reverse(String str)

    {

        // return if the string is null or empty

        if (str == null || str.equals("")) {

            return str;

        }

        // create a character array and initialize it with the given string

        char[] c = str.toCharArray(); 

        for (int l = 0, h = str.length() - 1; l < h; l++, h--)

        {

            // swap values at `l` and `h`

            char temp = c[l];

            c[l] = c[h];

            c[h] = temp;

        } 

        // convert character array to string and return

        return String.copyValueOf(c);

    }

    public static void main(String[] args)

    {

        String str = "Techie Delight";

        // String is immutable

        str = reverse(str);

        System.out.println("The reverse of the given string is: " + str);

    }

}

Output

Java_Reverse_string

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Using the Java Collections Framework reverse() Method

You can use Collections.reverse() to reverse a Java string. Use these steps:

  1.       Create an empty ArrayList of characters, then initialize it with the characters of the given string with String.toCharArray().
  2.       Reverse the list by employing the java.util.Collections reverse() method.
  3.       Finish up by converting the ArrayList into a string by using StringBuilder, then return.

Code

import java.util.List;

import java.util.ArrayList;

import java.util.Collections;

import java.util.ListIterator;

class Main

{

    // Method to reverse a string in Java using `Collections.reverse()`

    public static String reverse(String str)

    {

        // base case: if the string is null or empty

        if (str == null || str.equals("")) {

            return str;

        }

        // create an empty list of characters

        List<Character> list = new ArrayList<Character>(); 

        // push every character of the given string into it

        for (char c: str.toCharArray()) {

            list.add(c);

        }

         // reverse list using `java.util.Collections` `reverse()`

        Collections.reverse(list);

        // convert `ArrayList` into string using `StringBuilder` and return it

        StringBuilder builder = new StringBuilder(list.size());

        for (Character c: list) {

            builder.append(c);

        } 

        return builder.toString();

    }

     public static void main(String[] args)

    {

        String str = "Techie Delight";

         // String is immutable

        str = reverse(str);

        System.out.println("The reverse of the given string is: " + str);

    }

Output

Java_Reverse_string

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Conclusion

String objects in Java are immutable, which means they are unchangeable. Java works with string in the concept of string literal. When one reference variable changes the value of its String object, it will affect all the reference variables.

The string class is more commonly used in Java In the Java.lang.String class, there are many methods available to handle the string functions such as trimming, comparing, converting, etc. These methods also help you reverse a string in java.

You have now seen a vast collection of different ways to reverse a string in java. There are also a few popular third-party tools or libraries such as Apache Commons available to reverse a string in java.

If you are looking to master Java and perhaps get the skills you need to become a Full Stack Java Developer, Simplilearn’s Full Stack Java Developer Master’s Program is the perfect starting point. This six-month bootcamp certification program covers over 30 of today’s top Java and Full Stack skills. The curriculum sessions are delivered by top practitioners in the industry and, along with the multiple projects and interactive labs, make this a perfect program to give you the work-ready skills needed to land today’s top software development job roles.

If you have any feedback or suggestions for this article, feel free to share your thoughts using the comments section at the bottom of this page. Our experts will review your comments and share responses to them as soon as possible. 

Happy Learning!

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 16 Dec, 2024

6 Months$ 8,000
Automation Test Engineer Masters Program

Cohort Starts: 27 Nov, 2024

8 months$ 1,499
Full Stack Java Developer Masters Program

Cohort Starts: 18 Dec, 2024

7 months$ 1,449
Full Stack (MERN Stack) Developer Masters Program

Cohort Starts: 8 Jan, 2025

6 Months$ 1,449