Java Program to Reverse a Given String
This page contains a Java program that reverses a given string. The program uses basic string manipulation techniques to achieve this task.
Program Explanation
The Java program to reverse a string follows these steps:
- Define the main class: Create a public class named
ReverseString
. - Main Method: The
main
method is the entry point of the program. - Input String: Define a string that you want to reverse.
- Reverse the String: Use a loop to reverse the string by iterating from the end to the beginning.
- Print the Result: Output the reversed string to the console.
Java Program Code
/**
* Java program to reverse a given string.
*/
public class ReverseString {
/**
* Main method which is the entry point of the program.
* @param args command-line arguments
*/
public static void main(String[] args) {
// Define the string to be reversed
String original = "Hello, World!";
// Call the reverse method and store the result
String reversed = reverseString(original);
// Print the reversed string
System.out.println("Original String: " + original);
System.out.println("Reversed String: " + reversed);
}
/**
* Method to reverse a given string.
* @param str the string to be reversed
* @return the reversed string
*/
public static String reverseString(String str) {
// Create a StringBuilder object with the original string
StringBuilder sb = new StringBuilder(str);
// Reverse the string using the StringBuilder reverse method
return sb.reverse().toString();
}
}
Program Details
The ReverseString
class contains the following:
main
Method: The entry point of the program where the string is defined and the reverse method is called.reverseString
Method: A static method that takes a string as input, reverses it using theStringBuilder
class, and returns the reversed string.
Running the Program
To run the program:
- Save the code in a file named
ReverseString.java
. - Compile the program using the command:
javac ReverseString.java
. - Run the compiled program using the command:
java ReverseString
.
Explanation of the Java Program:
- Class Definition: The class
ReverseString
contains all the methods and logic needed to reverse the string. - Main Method:
- Initializes a string
original
with a value to be reversed. - Calls the
reverseString
method and stores the result inreversed
. - Prints both the original and reversed strings to the console.
- Initializes a string
- reverseString Method:
- Uses
StringBuilder
, a mutable sequence of characters, which allows efficient manipulation of the string. - The
reverse()
method ofStringBuilder
reverses the characters. - Returns the reversed string as a new string.
- Uses