Q.
Write a java program to reverse a string
Here is a simple Java program to reverse a given string:
Java Program to Reverse a String
import java.util.Scanner;
public class ReverseString {
public static void main(String[] args) {
// Create a scanner object to take input from the user
Scanner scanner = new Scanner(System.in);
// Ask the user to input a string
System.out.print("Enter a string: ");
String input = scanner.nextLine();
// Call the reverseString method and print the reversed string
String reversed = reverseString(input);
System.out.println("Reversed String: " + reversed);
// Close the scanner to avoid resource leak
scanner.close(); }
// Method to reverse the given string
public static String reverseString(String str) {
StringBuilder reversed = new StringBuilder(str);
return reversed.reverse().toString(); // Reverse and return the string }}
Explanation:
1. Input:
The program uses a Scanner to take user input for the string to be reversed.
2. String Reversal:
The reverseString method takes the input string and uses the StringBuilder class to reverse the
string. The StringBuilder.reverse() method is a built-in function that reverses the characters of
the string.
3. Output:
The reversed string is printed on the console.
Sample Output:
Enter a string: Hello
Reversed String: olleH
Conclusion:
This program successfully reverses the input string using the StringBuilder class, which is
efficient for string manipulation in Java. You can also achieve string reversal using other
methods, such as using loops, but StringBuilder.reverse() is the most straightforward and
efficient approach.