How to reverse a string in Java
We often come across situations where we are required to reverse the characters of a string.
This can be achieved using multiple approaches. However, the most straightforward approach is using the reverse() method, which is a built-in method of the java.lang.StringBuilder class in Java.
Code
To reverse the characters of a String object, we first need to convert it to a mutable StringBuilder object.
Next, we need to call the reverse() method to reverse the character sequence of the string.
Finally, we can obtain the reversed string from the StringBuilder object by calling the toString() method on it.
Let’s look at the code snippet below to understand this better.
class Reverse {public static void main( String args[] ) {// string to be reversed.String str = "Hello";// Converting the string to StringBuilder objectStringBuilder sb = new StringBuilder(str);// Reversing the stringsb.reverse();// object to store reversed stringString revStr = sb.toString();// printing reversed stringSystem.out.println(revStr);}}