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.
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);
}
}
The output of the above program will be:
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);
}
}
The final output of above program will be:
The reversed string will be: ahgeM si emaN yM