➤ Sum of digits in a String
➤ Count No of Vowels String
➤ String Pattern Programs in Java
➤ Take String Input In Java
➤ Take Multiple String Input in Java
➤ How To Reverse a String In Java
➤ Remove Special Characters
➤ String – Remove Character
➤ String Palindrome In Java
➤ Sort String In Java
➤ How to Compare Strings In Java
➤ Second Occurrence of Character
➤ Replace nth Occurrence String
➤ Last Occurrence of Character
➤ Uppercase & Lowercase
➤ Java Check If Char is Uppercase
➤ Check If String is Uppercase
➤ Swap Characters in String Java
➤ Java String indexOf() Method
➤ How to Replace Dot in Java?
➤ How to Find Length of String
➤ Substring Method In Java
➤ Split Method 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!