10 Ways to Reverse a String in Java

10 Ways to Reverse a String in Java

Introduction

Java is the most widely used programming language. Java is one of the most popular programming languages, but it is also one of the most efficient. Previously, Java was not widely used and was not included in the school curriculum. However, I believe that the Java programming language is the most incredible option if you want to become a developer who can construct quick and efficient programs right away.

The language’s syntaxes are quite extensive. To print something, for example, write “System.out.println();”. It may appear to be difficult, but it is just temporary. After you’ve written a few applications, you’ll remember these syntaxes subconsciously. These issues are minor compared to the value this language delivers to developers.

There are various operations to perform on a string. However, the widely used is the reverse of a string. There are many ways to reverse a string in Java. So, in this article, we will discuss how to reverse a string in Java.

Firstly, let us understand string. In Java, a string is a collection of characters that behave like an object. After arrays, the string is one of the most often used data structures. It’s a character array-based object that saves data.

The Java language package is required to build a string object. Strings are unchangeable, meaning their internal state does not change after the object has been entirely constructed. The string object can execute various actions, but in Java, reverse strings are the most commonly utilized. So, further we will know how to reverse a string in Java.

Java Homework Help – Secure Your Grades with Best Assistance.

How to Reverse a String in Java?

In Java, there are several methods for reversing a string. Let us discuss some of them:

By Using toCharArray():

One way to reverse a string in Java is to use the toCharArray() function. The length variable, which gives the overall length of the string variable, is also used in the code. The for loop iterates until the string index zero is reached.

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

Using StringBuilder:

The reverse() method in the StringBuilder class reverses the characters in the string. The characters are replaced in reverse order using this procedure. In Java, the reverse method is a static method that implements the logic for reversing a string. So, you can reverse a string in Java using this method.

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:

Reversed string: tnednepednI

By using StringBuffer:

The String class requires a reverse() function. Therefore use the StringBuffer method to convert the input string to a StringBuffer. Then, to reverse the string in Java, use the reverse() method.

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

Using While-Loop or For-Loop:

Use the while or for loops to manipulate the string. Using a cursor move, determine the length of the string, or iterate through the string’s index and end the loop. The loop outputs the character from the string at index (i-1). The loop begins and repeats the string length until index 0 is reached. This way, you can reverse a string in Java using loops.

Code for 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: tuptuO gnirtS yM

Code for 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: gnirtS weN yM

Using ArrayList Object:

Convert the input string to a character array using the built-in function toCharArray(). After that, add the array’s characters to the ArrayList object. In Java, the Collections class contains a built-in reverse() function. Because the reverse() method of the Collections class requires a list object, reverse the list using the ArrayList object, which is a list of characters.

In the code below, copy the String contents into an ArrayList object. Make a ListIterator object by calling the listIterator() method on the ArrayList object. Use the ListIterator object to iterate across an array. It also makes it easier to traverse through the inverted list, printing each object on the output screen. This way, you can reverse a string in Java.

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: gnirtS a esreveR

Converting String to Bytes:

The splitBytes() method splits or converts a string into bytes. The length of the temporary byte array will be the same as the length of the specified string. Reverse the bytes and place them in a different byte array. getBytes() is a built-in method for converting a string to bytes. Two-byte arrays are constructed, one to hold the converted bytes and the other to record the reversed result.

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:

Reversed string: tnednepednI

Using Recursion:

Because the stack is involved, we can quickly transform the code using the recursive call stack. We must first change the string into a character array because it is immutable. After that, we reverse the character array and complete the process by converting the character array back to a string.

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:

The reverse of the given string is: thgileD eihceT

Using CharacterArray:

We cannot alter a string as its unchangeable. However, we can reverse it using CharacterArray. Make a character array equal to the length of the string. Then, using the string’s characters, fill the character array backwards. Last but not least, use string to convert the character array to a string. Then return it with copyValueOf(char[]).

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:

The reverse of the given string is: thgileD eihceT

Using Substring() Method:

The String.substring(int, int) function can be used to reverse a string in Java recursively. Let us look at the code.

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

    }

}

Output:

The reverse of the string is: thgileD eihceT

Using the Java Collections Framework Reverse() Method:

To reverse a Java string, use Collections.reverse(). Create an empty ArrayList of characters first, then use String.toCharArray to fill it with the characters from the specified string (). Then, using the java.util.Collections reverse() function, reverse the list. Finally, return after transforming the ArrayList to a string using StringBuilder.

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:

The reverse of the given string is: thgileD eihceT

Conclusion

Although string objects in Java are immutable, the concept of a string literal is used in Java. When the value of a reference variable’s string objects changes, it affects all other reference variables.

In Java, the string class is more widely used. In the Java.lang package, many methods are available in the String class to handle string functions such as trimming, comparing, converting, etc. These techniques can also be used to reverse a string.

We have discussed the possible methods to reverse a string in java. There are many other blogs related to Java. If you want to learn and master Java, please check out those and feel free to contact us.

Leave a Comment

Your email address will not be published.