In this tutorial, we will learn about 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
In a Java program to reverse a string, the program reverses each alphabet and we get an output as the reversed string. For example, if we wish to reverse: βMy name is Meghaβ. The output string of this will be:βym eman si ahgemβ. There some very interesting things that you need to know before understanding the program. Some of them are:
- The objects of a string are always immutable as all the objects of the string are cached in a pool of string. When stored in hashmap, it becomes easier to fetch the value.
- In Java, we donβt have a reverse() method to reverse a string. However, we can use reverse() using a string builder class.
- toCharArray() method is not present in string builder class whereas string class has toCharArray() method.
We can reverse a string by the following methods:
- By using recursion: A process that is able to call itself, again and again, is called recursion.
- Using a byte Array.
- Using while loop
- we can do it using for loop.
- We can also perform the reverse of a string by word to word.
- Using Java reverse() function
- Using the String Buffer Class Approach
Java Program to reverse a string using For Loop
Weβll need to create a new empty String object to store the reversed string because we cannot alter or reverse the original string in place due to its immutability.
With the loop, we can use a for loop or a while loop to iterate over each of the string characters. In this example weβll use a for loop.
Next, we need to configure our loop to access the string characters in reverse order. After all, we want a Java program to reverse a string!
We can do this with a decrementing loop: this starts at the last index (character) of the string object, then decrements on each loop until it reaches the 0th index (the first char).
To find the last charβs index we can use Javaβs built-in .length() string method to find the length of our string, and then we subtract 1 to account for 0 indexing. Our for loop counter variable will start at this index and decrement by -1 in each iteration.
Having set up the loop, we can iterate over the string and access the chars in reverse order. The final step is to store the chars in the empty string we created. To do this, we concatenate each char with the current version of the string. When weβre finished weβll have a new string object with the chars in reverse.
Code :
public class Developerhelps {
public static void main(String[] args) {
String stringExample = "DeveloperHelps";
System.out.println("Original string: "+stringExample);
int n = stringExample.length(); // Length of original string
String reversedString =""; // Empty string to store reversed chars
char ch; // Char to store current string character
for (int i = n - 1; i >= 0; i--) {
ch = stringExample.charAt(i); // Return & store current char
reversedString = reversedString + ch; // Append char to end
}
System.out.println("Reversed string: "+ reversedString);
}
}
Output :
Original String: DeveloperHelps
Reversed string: spleHrepoleveD
Below is a program for better understanding of how we can reverse a string using Java.
public class JavaExample {
public static void main(String[] args) {
String str = "My Name is Megha";
String reversed = reverseString(str);
System.out.println("The reversed string is: " + reversed);
}
public static String reverseString(String str)
{
if (str.isEmpty())
return str;
return reverseString(str.substring(1)) + str.charAt(0);
}
}
Output :
The reversed string will be: ahgeM si emaN yM
Now, below is a program to reverse a string using reverse() string builder method.
import java.lang.*;
import java.io.*;
import java.util.*;
class Developerhelps
{
public static void main(String[] args)
{
String input = "My Name is Megha";
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1.reverse();
System.out.println("The reversed string will be:" + input1);
}
}
Output :
The reversed string will be: ahgeM si emaN yM
Reverse a String in Java using String Buffer Class Approach
In string buffer class, we have a built-in reverse() method, which can be used to reverse the string java. This method takes in a string object as a parameter and returns the reversed string. We will use this in-built method in this approach to reverse the string.
import java.util.*;
public class ReverseString {
public static String rev(String s) {
return new StringBuilder(s).reverse().toString();
}
public static void main(String args[]) {
String s1 = "DeveloperHelps";
System.out.println("Initial String: " + s1);
s1 = rev(s1);
System.out.println("Reversed string: " + s1);
}
}
Output :
Initial String: DeveloperHelps
Reversed string: spleHrepoleveD
Explanation :
(1) This Function reverses the string in Java using StringBuilder
(2) We are passing the string ‘s’ in the constructor of StringBuilder to create a new object of StringBuilder Class. The string ‘s’ will remain unchanged.
(3) s1 will contain the initial string.
(4) Reversing the string using StringBuilder class
(5) At last printing the result
Complexities :
Time Complexity: O(n)
Space Complexity: O(1)