Java program to reverse a string

Java program to reverse a string

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

Java Programs with Examples and Output

1.) Java program to get IP address

2.) Factorial Program in Java

3.) Java program to reverse a string

4.) Java Program to Convert Kilometers(KMS) to Miles

5.) Swap two numbers using bitwise operator

Leave a comment

Your email address will not be published. Required fields are marked *