Reverse String Java

In Java, a string is a group of characters that acts like an object. After arrays, the string is one of the most popular and widely used data structures. The information is kept in this object as a character array.

Simply think of a string as a character array to simplify things and see how many string-based issues may be resolved.

You require java.lang in order to build a string object.

String type. A string is represented by UTF-16 in Java programming. Since strings cannot be changed once they have been completely generated, their internal state does not change. Although the string object may execute a number of actions, the most used one in Java is to reverse strings. Join the Java training in Chennai under the subject matter specialists to learn every concept of Java programming language.

1Reverse in Java

Instance: Reverse the WELCOME string to produce EMOCLEW.

.

2In Java, how do you reverse a string?

Strings are immutable objects, therefore reversing them requires starting over with a new string. The string class lacks a reversal function. A toCharArray() function is provided for doing the reverse.

2.1With the use of toCharArray ()

Here’s some code that will show you how to turn a string around. To invert a string, you can use Java’s toCharArray() function.

The code also makes use of the length function, which, when called with a string variable, returns the variable’s full length.

This for loop will keep going until index 0 of the string no longer exists.

Code

//ReverseString using Character Array.

public static void main(String[] arg) {

// declaring variable

String stringinput = “INDIA”;

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

3Using the StringBuilder

Consider the StringBuilder class and how it can be used to reverse a string. StringBuilder and StringBuffer both include a built-in method called reverse() that can be used to reverse the characters in a string. This method effectively switches around the order of the characters. The static method in Java that can reverse a string around is named reverse.

The code examples provided here make use of the StringBuilder class object.

StringBuilder objects run quickly, use little memory, and may be customized. It also considers these things to be thread-unsafe.

This object uses its own reverse() function to achieve our goals.

Java users are encouraged to use this method, as it is the most reliable for reversing strings.

Code:

//ReverseString using StringBuilder.

public static void main(String[] arg) {

// declaring variable

String input = “HELLO”;

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

Another option is to use the reverse() method of the StringBuffer class, which is functionally equivalent to the StringBuilder. You can use either the StringBuilder or StringBuffer classes in Java to perform a backslash operation on a string. Both share a similar approach to the topic of reversal. In contrast to StringBuffer, the StringBuilder class is widely regarded as superior. The StringBuilder class is more efficient and does not require synchronization. These StringBuilder and StringBuffer classes generate malleable strings of characters. To achieve your goal, use the reverse() method.

Because of the immutable nature of the Java language’s String class, any operation on a string will result in the instantiation of a new string object. StringBuilder and StringBuffer are two utility classes in Java that coordinate shared resources for string operations.

4Using a while loop, a for loop, or both

When working with strings, only use the while loop or the forloop. Find the string’s length by either moving the cursor to the end or iterating through the index.

Wherever the index  (i-1) is in the string, the loop will print that character.

The loop starts then proceeds to iterate over the entirety of the string and finally stops at index 0. To improve your career prospects, join Java training in Chennai.

4.1Code Using While Loop

//  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 = “INDIA IS MY COUNTRY”;

//Get the String length

 int iStrLength=stringInput.length();

//Using While loop

while(iStrLength >0)

{

System.out.print(stringInput.charAt(iStrLength -1));

iStrLength–;

}

 }

}

Output :

yrrehC si emaN yM

5Making Use of String-to-Byte Conversion

The getBytes() function can be used to create byte arrays from strings. The length of the provided string will be used to determine the size of the intermediate byte array. This time, we want to get the bytes backwards and save them in a new byte array.

The string is temporarily stored in a byte array in the following code. There is also a built-in method, getBytes(), that can be used to perform the conversion from string to bytes. One byte array is made to keep track of the original bytes and another to keep track of the reversed result. If you want to learn thoroughly about Java, join our Java training in Chennai.

Code

//ReverseString using ByteArray.

public static void main(String[] arg) {

// declaring variable

String inputvalue = “SMILE”;

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

ELIMS

6Utilizing the ArrayList Object

The input string can be transformed into a character array with the help of the in-built toCharArray() method. You can then insert the array’s characters into an object of type ArrayList. The reverse() method is a standard feature of Java’s Collections class. To reverse a list, utilize the ArrayList object, which is a list of characters, with the reverse() function of the Collections class.

In the following code, the contents of the String are copied into an ArrayList object. Make a ListIterator object by calling listIterator() on the ArrayList object. The ListIterator object can be used to iterate through the array. It’s also useful for printing each item in the inverted list on the output screen one by one. Enroll in the Java course in Chennai to upgrade your skills and improve your employability.

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 = “Java Training in Chennai”;

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:

iannehC ni gniniarT avaJ

Sign up with the best Java training institute in Chennai and grow greater.

7Utilizing StringBuffer

For the String class to have a reverse() method, the input string must first be converted to a StringBuffer using the StringBuffer method. Then, you may flip the string by invoking the reverse() function.

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 = “REVERSE”;

        // conversion from String object to StringBuffer

        StringBuffer sbfr = new StringBuffer(str);

        // To reverse the string

        sbfr.reverse();

        System.out.println(sbfr);

    }

}

Output: 

ESREVER

8By Using Stack

Using the Stack data structure, a Java string can be reversed in the following ways:

Construct a character-free stack.

Push each character from the string into a stack after first converting it to a character array using the String.toCharArray() method.

When the stack is empty, remove its contents and place them in a character array. In this case, the characters will enter backward.

Then, return the newly generated string by converting the character array to a string with String.copyValueOf(char[]).

Joining our Java training in Chennai trains you to master every concept of Java.

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 = “Java is Everywhere”;

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

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

    }

}

Output

erehwyrevE si avaJ

9Utilizing a Character Array

Given that the Java implementation of the string type is immutable, we are unable to make any modifications to the string object. However, a character array can be used:

Create a string-sized array of characters.

Fill the reverse-order character array with the string’s characters.

Employing String to transform the array of characters into a string.

Return the value from copyValueOf(char[]).

Enroll in the Java course in Chennai to understand java concepts in depth.

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 = “Learn Java Course in Chennai “;

        // String is immutable

        str = reverse(str);

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

    }

}

Output

iannehC ni esruoC avaJ nraeL

10Making Use of Recursion

To understand how to invert a string in Java, read this article. Since the stack is involved in recursion, the code may be easily converted. We need to first turn the string into a character array because the string is immutable. Finally, we invert the character array and return to string form to complete the process.

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 = “Learn java”;

        // string is immutable

        str = reverse(str);

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

    }

}

Output

avaJ nraeL

11Using the Substring() Technique

Java’s String.substring(int, int) function allows programmers to perform recursive string reversal. Here’s one way to go about it:

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 = “Software Engineer”;

        // string is immutable

        str = reverse(str);

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

    }

}

12By Using a Character Array and the swap() Function

Here’s a quick method for inverting a Java string using character arrays.

To begin, use String.toCharArray to generate a character array and populate it with the characters from the target string ().

Run the loop from the two extremes (1, h) until they meet in the middle. The values at positions “l” and “h” should be exchanged in each loop iteration. Change the value of “l” up and “h” down.

Finally, return after you have converted your character array to a string using String.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;

        }

        // 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 = “Task Manager”;

        // String is immutable

        str = reverse(str);

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

    }

}

Output

reganaM ksaT

13Reversing with the Java Collections Framework reverse() Method

In Java, you can reverse a string with the help of the Collections.reverse() method. Following these directions can help you:

Build a new character array and fill it with the characters from the supplied string using the String.toCharArray method ().

Use the java.util.Collections reverse() function to flip the items in the list.

Finally, return after using StringBuilder to transform the ArrayList into a string.

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 = “Java Developer”;

         // String is immutable

        str = reverse(str);

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

    }

}

Output

repoleveD avaJ

14Conclusion

Java’s string objects are immutable, so you can’t modify them. The concept of a string literal is used in Java when working with strings. Every reference variable is affected by a change to any one of them that modifies its String object value.

Java programmers typically utilize the string class. Specifically, in Java. lang. In the String class, you’ll find numerous options for dealing with common string-related tasks like trimming, comparing, converting, etc. You may also use these methods to invert a string in Java.

You have now been exposed to a large variety of strategies for reversing a string in Java. For the purpose of reversing a string in Java, there are also a few well-known third-party tools or libraries available.

SLA’s Full Stack training in Chennai is an excellent place to begin if you want to learn Java and develop the skills necessary to work as a Full Stack Java Developer. This program is ideal for giving you the work-ready skills necessary to land today’s top software development job roles because the curriculum sessions are presented by leading practitioners in the field and because it includes various projects and interactive labs.