Java is one of the most demanding and widely used programming languages. Web developers prefer using Java because of its various features and high-end programming tools.
Edureify, the best AI Learning App has provided various informative articles on different tools of Java. In this article, Edureify brings information on the different ways to reverse a string in Java.
Read on to know more.
What is a String in Java?
String in Java is a sequence of characters that behave like an object. After Array, String is the most common and used data structure. The string is an object that stores the data in a character array.
The string can be considered as a character array wherein many string-based problems can be solved. One needs the java.lang.String class to create a string object. The UTF-16 is used by Java programming to represent a string. A string’s internal state remains constant even after the object is created completely for its immutable quality.
The string object can perform various operations. Out of all the operations of string, reverse string in Java is the most commonly used function.
What is Reverse String in Java?
Much like the name suggests, the reverse function in Java flips or reverses the order of the character. The reverse string function makes the string read backward.
Example:
EDUREIFY in String Reverse function will give the output as YFIERUDE
Ways to Reverse a String in Java
There are different ways to reverse a string in Java. The following are the different ways to reverse a string in Java along with examples.
By using toCharArray()
The strings are immutable objects. It means one needs to create another string to reverse them. The string class does not have a reverse method to reverse a string. The toCharArray() method helps to reverse a string. Read the following code to better understand-
Code-
//ReverseString using Array. public static void main(String[] arg) { // declaring variable String inputstr= “Kolkata”; // convert String to character array // by using toCharArray char[] reslt = inputstr.toCharArray(); // iteration for (int i = reslt.length – 1; i > = 0; i--) // print reversed String System.out.print(reslt[i]); } Output- atakloK
By using StringBuilder
StringBuilder is another method to reverse a string in Java. The StringBuilder or StringBuffer class method replaces the sequence of the characters in reverse order.
Here are some features of the StringBuilder function-
- It is a static method that has the logic to reverse a string in Java
- StringBuilder objects are mutable
- They are memory efficient and quick in execution but it also considers the objects as not thread-safe
- The objects call the in-built reverse() to bring the desired output
- This method is highly preferred and most common in use to reverse a string in Java
Code-
//ReverseString using StringBuilder. public static void main(String[] arg) { // declaring variable string input= “Edureify”; // creating StringBuilder object StringBuilder stringbuildervariable = new StringBuilder(); // append a string into StringBuilder stringbuildervarible // append is inbuilt method to append the data stringBuildervarible.append(input); // reverse is built method in StringBuilder to use reverse the string stringBuildervarible.reverse(); // print reversed String System.out.printIn( “Reversed String : “+stringBuildervarible); } Output- Reversed String: Yfierude
Similarly, the StringBuffer class reverse() method can also be used. The StringBuilder and StringBuffer classes work in the same way to reverse a string in Java. Between these two, the StringBuilder class is faster and not synchronized. Developers prefer using the StringBuilder class.
By using While Loop or For Loop
Handling the string within the while loop or the for loop is simple.
The following codes show how the loop function works-
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- tuptuO gnirtS yM
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- gnirtS weN yM
By Converting a String to Bytes
The getBytes() method splits or converts the given string into bytes. The temporary byte array length remains equal to the length of the given string.
Code-
// ReverseString using ByteArray public static void main(String[] arg) { // declaring variable String inputvalue = “Universal”; // 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.printIn( “Reversed String : “ +new String(resultoutput)); } Output- Reversed String- Lasrevinu
By Using ArrayList Object
The built-in method toCharArray() converts the input string into a character array. Using the listIterator() method on the ArrayList object after the ArrayList object code constructs a ListIterator Object.
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.ad(c); Collections.reverse(revString); ListIterator li= revString.listIterator(); while (li.hasNext()) System.out.print(li.next()); } } Output- gnirtS a esreveR
By Using StringBuffer
The String class needs a reverse() function. Therefore, one needs to first convert the input string into a StringBuffer by using the StringBuffer method and 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 = “Edureify”; // conversion from String object to StringBuffer StringBuffer sbfr = new StringBuffer(str); // To reverse the string Sbfr.reverse(); System.out.printIn(sbfr); } } Output- yfierudE
By Using Stack
One can use the Stack data structure to reverse a Java string with the following steps-
- Create a stack that is empty of characters
- Using the String.toCharArray() method convert a given string into a character array and then place each character into the stack
- Take the characters out of the stack until it is empty and then assign the characters back into a character array
- Finally, convert the character array into a string by using String.copyValueOf(char[]) and then return the string that is formed
By Using Character Array
In Java, String is immutable. This feature does not enable making changes in the string object. The following are the ways to use Character Array to reverse a string in Java-
- Make the character array and the string of the same size
- Fill the character array backward by using the characters of the string
- Use the String.copyValueOf(char[]) to convert the character array into string
By using Recursion
Using the recursion call stack one can effortlessly convert the code.
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]; } } 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 character a character array char[] A = str.toCharArray(); // reverse character array reverse(A, O); // 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.printIn(“The reverse of the given string is: “ + str); } } Output- The reverse of the given string- thgileD eihceT
Using the Character Array and Swap() method
The following states an efficient way of using character arrays to reverse a Java String-
- Begin with creating your character array and initializing it with the characters of the string by using String.toCharArray()
- Begin from the two endpoints ‘1’ and ‘h’ and run the loop until they intersect. While iterating each of the loops, swap the values present at indexes “l” and “h”. increment “l” and decrement “h”.
- Using the String.copyValueOf(char[]) convert the character array into string
Here were the different ways to reverse strings in Java.
Java has been one of the most popular programming languages reason being its various lucrative features that aid developers in efficiently developing applications. Learning Java is beneficial to many due to its various job opportunities and lucrative salary like-
- Full Stack JAVA Developer- 20,000 to 70,000 pay
- Web Developer and Programmer- 12,000 to 30,000 a month
- Java Programmer- 3,00,000 to 8,00,000 a year
- Mobile App developer- 5,00,000 to 8,00,000 a year (for freshers)
- Java and J2Ee Programmer, Advanced- 10,00,000 to 20,00,000 a year
Some of the other career opportunities with Java are-
- Developing enterprise application
- Desktop GUI Application
- Games Developer
- Scientific Applications, etc.
Some of the top companies that are demanding skilled Java Programmers are-
- Tata Consultancy Services– 335 vacancies
- Cognizant Technology Solutions– 5.2T vacancies
- Capgemini– 9.5T vacancies
- Infosys– 3.7T vacancies
Edureify with its coding job-ready courses aims to provide the best platform to students who would like to secure their future in the IT industry. With the coding job-ready courses offered by Edureify, students will benefit from the following-
- Get 200+ learning hours
- Learn from the industry experts
- Have their doubts cleared instantly
- Get job and career guidance
With Edureify’s Java courses, students can learn about the different features of Java, like Java Arrays, Polymorphism in Java, Encapsulation in Java, Inheritance in Java, and more. Take the coding courses with Edureify and kickstart your Java programmer career soon.
Some FAQs on Reverse String in Java-
1. What is a String in Java?
String in Java is a sequence of characters that behave like an object. After Array, String is the most common and used data structure. The string is an object that stores the data in a character array.
2. What is Reverse String in Java?
Much like the name suggests, the reverse function in Java flips or reverses the order of the character. The reverse string function makes the string read backward.
3. Give an example of a Reverse String in Java.
HELLO in String Reverse function will give the output as OLLEH
4. Mention the steps of Character Array to Reverse String in Java.
The features of Character Array to Reverse String in Java are-
- Make the character array and the string of the same size
- Fill the character array backward by using the characters of the string
- Use the String.copyValueOf(char[]) to convert the character array into string
5. From where can I learn more about Java?
Edureify with its coding courses enables students to learn more about Java and other programming languages.