Here's a simple Java program to reverse a string:
public class ReverseString {
public static void main(String[] args) {
String original = "Hello, World!";
String reversed = reverseString(original);
System.out.println("Original string: " + original);
System.out.println("Reversed string: " + reversed);
}
public static String reverseString(String str) {
// Convert string to char array
char[] charArray = str.toCharArray();
// Initialize pointers for reversing
int left = 0;
int right = charArray.length - 1;
// Reverse the string
while (left < right) {
// Swap characters at left and right pointers
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
// Move pointers towards the center
left++;
right--;
}
// Convert char array back to string
return new String(charArray);
}
}
This program defines a `reverseString` method that takes a string as input and returns its reverse. In the `main` method, an example string "Hello, World!" is provided, and its reverse is printed out. You can replace `"Hello, World!"` with any string you want to reverse.