public class StringFormatter {
public static String reverseString(String str){
StringBuilder sb=new StringBuilder(str);
sb.reverse();
return sb.toString();
}
}
To reverse a string in Java, you can use several approaches. Here are two commonly used methods:
Method 1: Using StringBuilder or StringBuffer
public class StringReversal {
    public static void main(String[] args) {
        String input = "Hello, World!";
        StringBuilder reversed = new StringBuilder(input).reverse();
        String output = reversed.toString();
        System.out.println(output);
    }
}
In the code above, we create a StringBuilder object with the input string and use its reverse() method to reverse the characters. We then convert the reversed StringBuilder back to a string using toString(). Finally, we print the reversed string.
Method 2: Using a char array
public class StringReversal {
    public static void main(String[] args) {
        String input = "Hello, World!";
        char[] charArray = input.toCharArray();
        int start = 0;
        int end = charArray.length - 1;
                 while (start < end) {
            char temp = charArray[start];
            charArray[start] = charArray[end];
            charArray[end] = temp;
            start++;
            end--;
        }
                 String output = new String(charArray);
        System.out.println(output);
    }
}
In this approach, we convert the string to a character array using toCharArray(). Then, we initialize two pointers: start at the beginning of the array and end at the end of the array. We swap the characters at start and end positions while incrementing start and decrementing end until they meet in the middle. Finally, we create a new string from the reversed character array using new String(charArray) and print it.
Both methods yield the same output
These approaches provide different ways to reverse a string in Java. The first method using StringBuilder or StringBuffer is simpler and more concise, while the second method utilizing a char array demonstrates a manual reversal process.
