Reverse a String in Java Using StringBuilderReversing a string is a frequent job that can be carried out in a variety of ways in Java. One effective option is to reverse the contents of a string by using the StringBuilder class' reverse() function. In this section, we'll look at how to use StringBuilder in Java to reverse a string. Step 1: Create a StringBuilder instance To start, we need to create a StringBuilder instance that represents the string we want to reverse. We can do this by passing the string to the StringBuilder constructor as shown below: It creates a StringBuilder instance that contains the characters of the string str. Step 2: Reverse the string We may use the reverse() function to reverse the string's contents once we have the StringBuilder instance. A reference to the updated instance is returned by the reverse() method, which updates the contents of the StringBuilder instance while it is still in use. Afterwards, we can use the toString() method to return the StringBuilder instance to a string as seen below:. This will reverse the contents of the StringBuilder instance and store the reversed string in the reversedStr variable. Step 3: Display the reversed string Finally, we can display the reversed string to the user using the System.out.println() method or any other suitable output method. Here's an example of how to do it: It displays the reversed string to the user in the following format: Here's the complete code to reverse a string in Java using StringBuilder: StringReverser.java Output: The reversed string is: !dlrow ,olleH ConclusionWe have learned how to use StringBuilder in Java to reverse a string in this tutorial. An easy and quick way to reverse the contents of a string is provided by the StringBuilder class. You should be able to easily reverse any string by using the instructions provided in this article. Next TopicReverse Alternate Words in A String Java |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India