Reverse a string in Java

A string is a succession of characters that act like an article in Java. The string is quite possibly the most widely recognized and utilized datum structures after clusters. It is an item that stores the information in a person cluster. For better clearness, simply consider a string as a person cluster wherein you can tackle many string-based issues. To make a string object, the java.lang.String class is required. Java utilizes UTF – 16 to address a string. Strings are changeless with the goal that their inner state stays consistent after the item is altogether made. The string object performs different tasks, however the most generally utilized one is converse.

Java program to turn around a string that a client inputs. The charAt technique is utilized to get individual characters from the string, and we annex them in invert request. Tragically, there is no implicit technique in the “String” class for string inversion, however it’s very simple to make one.

In this fast instructional exercise, we will perceive how we can switch a String in Java. We’ll begin to do this handling utilizing plain Java arrangements. Then, we’ll examine the choices that the outsider libraries like Apache Commons give. Moreover, we’ll exhibit how to turn around the request for words in a sentence.

Turn around A String In Java – Here, we have examined the different strategies to invert a string utilizing java. The compiler has been added so you can execute the projects without help from anyone else, close by reasonable models and test yields. The strategies are as per the following:

The accompanying project to find switch a string has been written in five distinct ways. Assuming you do have any questions kindly let us know. Assuming that you want master assist with doing your java schoolwork appointed in school or college – if it’s not too much trouble, visit this site.

Java program to find an opposite a string – Using Static Method

  • Utilizing Array
  • Utilizing Recursion – in the event that assuming you have no clue look at the total aide here.
  • Utilizing While Loop
  • Utilizing For Loop – Tutorial With Examples
  • Utilizing Word by Word

How to reverse String in Java

There are many ways to reverse String in Java. We can reverse String using StringBuffer, StringBuilder, iteration etc. Let’s see the ways to reverse String in Java.

1) By StringBuilder / StringBuffer

File: StringFormatter.java

  1. public class StringFormatter {
  2. public static String reverseString(String str){
  3.     StringBuilder sb=new StringBuilder(str);
  4.     sb.reverse();
  5.     return sb.toString();
  6. }
  7. }

File: TestStringFormatter.java

  1. public class TestStringFormatter {
  2. public static void main(String[] args) {
  3.     System.out.println(StringFormatter.reverseString(“my name is khan”));
  4.     System.out.println(StringFormatter.reverseString(“I am sonoo jaiswal”));
  5.     }
  6. }

Output:

Features of Java – Javatpoint
nahk si eman ym
lawsiaj oonos ma I

2) By Reverse Iteration

File: StringFormatter.java

  1. public class StringFormatter {
  2. public static String reverseString(String str){
  3.     char ch[]=str.toCharArray();
  4.     String rev=“”;
  5.     for(int i=ch.length-1;i>=0;i–){
  6.         rev+=ch[i];
  7.     }
  8.     return rev;
  9. }
  10. }

File: TestStringFormatter.java

  1. public class TestStringFormatter {
  2. public static void main(String[] args) {
  3.     System.out.println(StringFormatter.reverseString(“my name is khan”));
  4.     System.out.println(StringFormatter.reverseString(“I am sonoo jaiswal”));
  5.     }
  6. }

Output:

nahk si eman ym
lawsiaj oonos ma I

Following are some interesting facts about String and StringBuilder classes :

1. Objects of String are immutable.
2. String class in Java does not have reverse() method, however StringBuilder class has built in reverse() method.
3. StringBuilder class do not have toCharArray() method, while String class does have toCharArray() method.

  • The idea is to traverse the length of the strin
  • Extract each character while traversing
  • Add each character in front of the existing string
// java program to reverse a word
import java.io.*;
import java.util.Scanner;
class GFG {
    public static void main (String[] args) {
      
        String str= "Geeks", nstr="";
        char ch;
      
      System.out.print("Original word: ");
      System.out.println("Geeks"); //Example word
      
      for (int i=0; i<str.length(); i++)
      {
        ch= str.charAt(i); //extracts each character
        nstr= ch+nstr; //adds each character in front of the existing string
      }
      System.out.println("Reversed word: "+ nstr);
    }
}
//Contributed by Tiyasa
  • Converting String into Bytes: getBytes() method is used to convert the input string into bytes[].
    Method: 
1. Create a temporary byte[]  of length equal 
   to the length of the input string.
2. Store the bytes (which we get by using 
   getBytes() method) in reverse order into 
   the temporary byte[] .
3. Create a new String abject using byte[] to
   store result.
// Java program to ReverseString using ByteArray.
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
    public static void main(String[] args)
    {
        String input = "";
        // getBytes() method to convert string
        // into bytes[].
        byte[] strAsByteArray = input.getBytes();
        byte[] result = new byte[strAsByteArray.length];
        // Store result in reverse order into the
        // result byte[]
        for (int i = 0; i < strAsByteArray.length; i++)
            result[i] = strAsByteArray[strAsByteArray.length - i - 1];
        System.out.println(new String(result));
    }
}
  • Using built in reverse() method of the StringBuilder class: String class does not have reverse() method, we need to convert the input string to StringBuilder, which is achieved by using the append method of StringBuilder. After that, print out the characters of the reversed string by scanning from the first till the last index.
// Java program to ReverseString using StringBuilder
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
    public static void main(String[] args)
    {
        String input = "";
        StringBuilder input1 = new StringBuilder();
        // append a string into StringBuilder input1
        input1.append(input);
        // reverse StringBuilder input1
        input1.reverse();
        // print reversed String
        System.out.println(input1);
    }
}

  • Converting String to character array: The user input the string to be reversed.
    Method:
1. First, convert String to character array
   by using the built in Java String class 
   method toCharArray().
2. Then, scan the string from end  to start, 
   and print the character one by one.
// Java program to Reverse a String  by
// converting string to characters  one
// by one
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
    public static void main(String[] args)
    {
        String input = "";
        // convert String to character array
        // by using toCharArray
        char[] try1 = input.toCharArray();
        for (int i = try1.length - 1; i >= 0; i--)
            System.out.print(try1[i]);
    }
}
  • Convert the input string into character array by using the toCharArray(): Convert the input string into character array by using the toCharArray() – built in method of the String Class. Then, scan the character array from both sides i.e from the start index (left) as well as from last index(right) simultaneously.
1. Set the left index equal to 0 and right 
   index equal to the length of the string -1.
2. Swap the characters of the start index 
   scanning with the last index scanning 
   one by one. After that, increase the left 
   index by 1 (left++) and decrease the right 
   by 1 i.e., (right--) to move on to the next 
   characters in the character array .
3. Continue till left is less than or equal to
   the right.
// Java program to Reverse a String using swapping
// of variables
import java.lang.*;
import java.io.*;
import java.util.*;
// Class of ReverseString
class ReverseString {
    public static void main(String[] args)
    {
        String input = "";
        char[] temparray = input.toCharArray();
        int left, right = 0;
        right = temparray.length - 1;
        for (left = 0; left < right; left++, right--) {
            // Swap values of left and right
            char temp = temparray[left];
            temparray[left] = temparray[right];
            temparray[right] = temp;
        }
        for (char c : temparray)
            System.out.print(c);
        System.out.println();
    }
}
  • Using ArrayList object: Convert the input string into the character array by using toCharArray() built in method. Then, add the characters of the array into the ArrayList object. Java also has built in reverse() method for the Collections class. Since Collections class reverse() method takes a list object, to reverse the list, we will pass the ArrayList object which is a type of list of characters.
1. We copy String contents to an object 
   of ArrayList.
1. We create a ListIterator object by using 
   the listIterator() method on the ArrayList 
   object.
2. ListIterator object is used to iterate over 
   the list.
3. ListIterator object helps us to iterate 
   over the reversed list and print it one 
   by one to the output screen.
// 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 = "";
        char[] hello = input.toCharArray();
        List<Character> trial1 = new ArrayList<>();
        for (char c : hello)
            trial1.add(c);
        Collections.reverse(trial1);
        ListIterator li = trial1.listIterator();
        while (li.hasNext())
            System.out.print(li.next());
    }
}

Output: 

  • Using StringBuffer: String class does not have reverse() method, we need to convert the input string to StringBuffer, which is achieved by using the reverse method of StringBuffer.
// Java program to demonstrate conversion from
// String to StringBuffer and reverse of string
import java.lang.*;
import java.io.*;
import java.util.*;
public class Test {
    public static void main(String[] args)
    {
        String str = "";
        // conversion from String object to StringBuffer
        StringBuffer sbr = new StringBuffer(str);
        // To reverse the string
        sbr.reverse();
        System.out.println(sbr);
    }
}

Also Read: How to Open URL in New Tab using JavaScript?

Leave a Reply

Your email address will not be published.