Write a Program To Reverse a String In Java

Write a Program To Reverse a String In Java | Reversing a string means reversing the position of characters in the given string. For example:- If the string is “Know” then after reversing, it will become “wonK”. We can perform this operation manually or Java has also provided some built-in or pre-defined method to reverse the string. 

The StringBuilder and StringBuffer class contain a reverse() method to reverse the string. We can use them to solve the problem.

Method prototype in StringBuilder class:- public StringBuilder reverse()

To call the reverse() method of the StringBuilder class on the String type value, we need to convert String into StringBuilder. While creating a StringBuilder object we can pass the string value and it will create a StringBuilder object. On a StringBuilder object, we can call the reverse() method to reverse the string, and after that using toString() we can convert the StringBuilder object to a String object.

public class Main {
   public static void main(String args[]) {
      String string =  "Hello World";

      // convert string to StringBuilder
      StringBuilder sb = new StringBuilder(string);

      // call reverse() function
      sb.reverse();
      
      // store result to String by
      // converting StringBuilder to String
      String reverse = sb.toString();
      
      // display strings
      System.out.println("Original String: " + string);
      System.out.println("Reversed String: " + reverse);
   }
}

Output:-

Original String: Hello World
Reversed String: dlroW olleH

Also see:- Different ways to Reverse a String In Java

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *