Java StringBuilder reverse() method is used to reverse a given character sequence.
Syntax of reverse() method:
sb.reverse(); //reverses the string represented by sb
Here, sb is an object of Java StringBuilder class.
reverse() Description
public StringBuilder reverse(): A StringBuilder instance represents a character sequence (a string). This method replaces the existing character sequence by reverse sequence.
reverse() Parameters
- This method does not take any parameter.
reverse() Return Value
- It returns a StringBuilder instance that contains the reverse of the given sequence.
Example 1: Reversing a String
public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder("Tomato"); System.out.println("Given String: "+sb); //reverse the String "Tomato" sb.reverse(); //print reverse string System.out.println("Reverse String: "+sb); } }
Output:
Example 2: Reversing user entered String
import java.util.Scanner; public class JavaExample { public static void main(String[] args) { StringBuilder sb = new StringBuilder(""); //take user input System.out.print("Enter any String: "); Scanner scan = new Scanner(System.in); String str = scan.nextLine(); sb.append(str); System.out.println("Entered String: "+sb); //reverse the user entered string sb.reverse(); //print reverse string System.out.println("Reverse String: "+sb); } }
Output: