How to reverse and output a string in Java?
You can reverse a string in Java using the reverse() method from the StringBuilder or StringBuffer class. Here is an example code:
public class StringReverseExample {
public static void main(String[] args) {
String str = "Hello World!";
// 使用StringBuilder类
StringBuilder sb = new StringBuilder(str);
sb = sb.reverse();
System.out.println(sb.toString());
// 使用StringBuffer类
StringBuffer sbf = new StringBuffer(str);
sbf = sbf.reverse();
System.out.println(sbf.toString());
}
}
Output result:
!dlroW olleH
!dlroW olleH
In the example above, we first created a string “str”, then we used the StringBuilder and StringBuffer classes to reverse it, and finally converted the reversed string to a string type using the toString() method. Finally, we used the System.out.println() method to output the reversed string.