We can help you develop your capabilities until you achieve your dream

Digital marketing

How to Reverse a String in Java:13 Best Methods

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.

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 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 stack = new Stack(); 

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

   


Source link

اترك تعليقاً

لن يتم نشر عنوان بريدك الإلكتروني. الحقول الإلزامية مشار إليها بـ *

زر الذهاب إلى الأعلى

Please turn off the ad blocker, as ads are the only source of our continuity

برجاء دعمنا عن طريق تعطيل إضافة Adblock