How To Reverse A String In Java

ExploreEXPLORE THE CATALOGSupercharge your career with 700+ hands-on coursesView All CoursesPythonJavaJavaScriptCReactDockerVue JSRWeb DevDevOpsAWSC#LEARNING TOOLSExplore the industry's most complete learning platformCoursesLevel up your skillsSkill PathsAchieve learning goalsProjectsBuild real-world applicationsMock InterviewsNewAI-Powered interviewsPersonalized PathsGet the right resources for your goalsLEARN TO CODECheck out our beginner friendly courses.PricingFor BusinessResourcesNewsletterCurated insights on AI, Cloud & System DesignBlogFor developers, By developersFree CheatsheetsDownload handy guides for tech topicsAnswersTrusted answers to developer questionsGamesSharpen your skills with daily challengesSearchCoursesLog InJoin for freeHow 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 object StringBuilder sb = new StringBuilder(str); // Reversing the string sb.reverse(); // object to store reversed string String revStr = sb.toString(); // printing reversed string System.out.println(revStr); } }Run

Relevant Answers

Explore Courses

Free Resources

License: Creative Commons-Attribution-ShareAlike 4.0 (CC-BY-SA 4.0)

Tag » How To Reverse A String In Java