Here, the input string is passed to the constructor of the StringBuilder object. Then, the reverse() method is called on the object, which reverses the order of the characters in the string. Finally, the toString() method is called on the StringBuilder object to convert it back to a string and return it.
StringBuffer is similar to StringBuilder, it is thread safe, whereas StringBuilder is not.
public static String reverseString(String s) {
StringBuffer sb = new StringBuffer(s);
return sb.reverse().toString();
}
The above approach is more efficient than the previous one that used a character array because it avoids the need to create a temporary array and copy the characters to it.
In both cases, the method takes a single string parameter and returns the reversed version of it.