How to reverse a string using StringBuffer in Java?

In Java, you can reverse a string using the reverse() method of the StringBuffer class. Here is an example:

public class Main {
    public static void main(String[] args) {
        String str = "Hello, World!";
        
        // 使用StringBuffer反转字符串
        StringBuffer stringBuffer = new StringBuffer(str);
        stringBuffer.reverse();
        
        // 输出反转后的字符串
        System.out.println(stringBuffer.toString());
    }
}

Output:

!dlroW ,olleH

In the example above, we start by creating a StringBuffer object and passing the original string to it as a parameter. Then, we reverse the string using the reverse() method. Finally, we convert the StringBuffer object back to a String using the toString() method and output the reversed string.

bannerAds