Full Stack Web Development Internship Program
- 29k Enrolled Learners
- Weekend/Weekday
- Live Class
String is a sequence of characters that is considered to be an object in Java. In Java, there are various operations that you can perform on the String object. One of the most widely used operations on a string object is String Reverse. In this article, I will tell you the various approaches to Reverse a String in Java.
In Java, a String can be reversed in five different ways. They are as follows:
Now let’s get into the details of each of these approaches starting off by understanding how to reverse a String in Java using CharAt method.
In the below given Java program will help you to understand how to reverse a String entered by the user. Here, I have used the CharAt() method in order to extract the characters from the input String. The main task of the CharAt() method is to return the character at the specified index in the given String. Then, I have appended them in reverse order to reverse the given String. It is one of the simple approaches to reverse a String in Java.
package Edureka; import java.util.*; public class StringReverse{ public static void main(String args[]) { String initial, rev=""; Scanner in=new Scanner(System.in); System.out.println("Enter the string to reverse"); initial=in.nextLine(); int length=initial.length(); for(int i=length-1;i>=0;i--) rev=rev+initial.charAt(i); System.out.println("Reversed string: "+rev); } }
When you execute this program, the output looks like as shown below:
Enter the string to reverse HELLO EDUREKA Reversed string: AKERUDE OLLEH
I hope you understood how to reverse a given Java String with this simple approach. Now let’s move further and understand how to reverse a String using String Buffer/ StringBuilder Class.
StringBuffer and StringBuilder comprise of an inbuilt method reverse() which is used to reverse the characters in the StringBuffer. This method replaces the character sequence in the reverse order. Below is the code to reverse a String using a built-in method of the StringBuffer class.
package Edureka; import java.util.*; public class StringRev{ // Function to reverse a string in Java using StringBuilder public static String rev(String s){ return new StringBuilder(s).reverse().toString(); } public static void main(String[] args){ String s= "Welcome to Edureka"; // Note that string is immutable in Java s= rev(s); System.out.println("Result after reversing a string is : "+s); } }
On executing the above code, the output will be as shown below:
Result after reversing a string is : akerudE ot emocleW
This is all about StringBuilder Class. Alternatively, you can also use a StringBuffer class reverse() method just like StringBuilder. Let’s take a look at the code below.
package Edureka; import java.util.*; public class StringRev{ // Function to reverse a string in Java using StringBuffer public static String rev(String s){ return new StringBufferr(s).reverse().toString(); } public static void main(String[] args){ String s= "Welcome to Edureka"; // Note that string is immutable in Java s= rev(s); System.out.println("Result after reversing a string is : "+s); } }
When you run the program, the output will the same as that of the StringBuilder class.
Note: You can either reverse as String using StringBuffer reverse() as shown in the above program or you can simply use the code logic as shown below:
StringBuffer sb =new StringBuffer("JavaEdureka"); System.out.println(sb.reverse()); Output: akerudEavaJ
Both StringBuilder and StringBuffer has the same approach of reversing a String in Java. But, StringBuilder is preferred as it is not synchronized and is faster than StringBuffer. Having understood this, let’s delve deeper into this article and learn one more approach to reverse a String in Java.
In this approach, I have first converted the given String to Character Array using CharArray() method. After that, I have just iterated the given array in the reverse order.
package Edureka; import java.util.*; public class StringRev{ // Function to reverse a string in Java public static String reverseString(String s){ //Converting the string into a character array char c[]=s.toCharArray(); String reverse=""; //For loop to reverse a string for(int i=c.length-1;i>=0;i--){ reverse+=c[i]; } return reverse; } public static void main(String[] args) { System.out.println(reverseString("Hi All")); System.out.println(reverseString("Welcome to Edureka Blog")); } }
llA iH golB akerudE ot emocleW
I hope you understood how to use reverse iteration approach to reverse a String in Java. Now let’s move further and understand reversing a String using recursion.
Recursion is nothing but a function that calls itself. In this approach, I will write a method which reverses the String by calling itself recursively. Let’s implement and check how it works.
package Edureka; import java.util.*; public class StringRecursion{ String rev(String str) { if(str.length() == 0) return " "; return str.charAt(str.length()-1) + rev(str.substring(0,str.length()-1)); } public static void main(String[ ] args) { StringRecursion r=new StringRecursion(); Scanner sc=new Scanner(System.in); System.out.print("Enter the string : "); String s=sc.nextLine(); System.out.println("Reversed String: "+r.rev(s)); } }
Enter the string : Java is the blooming technology since its existence Reversed String: ecnetsixe sti ecnis ygolonhcet gnimoolb eht si avaJ
In the above code, I created the object for the class StringRecursion r. Then, I have read the entered String using sc.nextLine() and stored it in the String variable s. Finally, I called the reverse method as r.rev(s). Having understood this, let’s now understand the last approach in this article. Here, I will tell you how to reverse the letters present in the given String.
This Java program reverses letters present in a String entered by the user. It doesn’t reverse the entire String as seen earlier in the previous approaches. For Example: Hello People will be termed as olleH elpoeP. Let’s implement the same using Java.
package Edureka; public class stringreverse { public static void main(String[] args) { // TODO Auto-generated method stub String str = "Welcome To Edureka"; String[] strArray = str.split(" "); for (String temp: strArray){ System.out.println(temp); } for(int i=0; i<3; i++){ char[] s1 = strArray[i].toCharArray(); for (int j = s1.length-1; j>=0; j--) {System.out.print(s1[j]);} System.out.print(" "); } } }
The output of the above program will be as shown below:
Welcome To Edureka emocleW oT akerudE
So, that was all about reversing the letters in the given String. This brings us to the end of the article on Reverse a String in Java. I hope you found it informative.
Java Strings Tutorial | String Manipulation in Java | Java Tutorial For Beginners | Edureka
Check out the Java Certification Course Online Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer.
Got a question for us? Please mention it in the comments section of this “Reverse a String in Java ” article and we will get back to you as soon as possible or join our Java Training in Padang.
Course Name | Date | Details |
---|---|---|
Java Course Online | Class Starts on 19th October,2024 19th October SAT&SUN (Weekend Batch) | View Details |
Java Course Online | Class Starts on 14th December,2024 14th December SAT&SUN (Weekend Batch) | View Details |
edureka.co