Reverse a String Using StringBuilder

      No Comments on Reverse a String Using StringBuilder




StringBuilder has a method reverse() which can be used to reverse a String. StringBuilder object can be created by passing String in the constructor of StringBuilder.

Syntax of reverse() Method:

Return type of this method is StringBuilder.

StringBuilder java.lang.StringBuilder.reverse()

This method Causes the character sequence to be replaced by the reverse of the sequence.

Steps to Program:

1.) Pass String into the constuctor of StringBuilder.
2.) Call reverse() method on the StringBuilder Object.
3) Call toString() method on the returned object of reverse() method.

Demo Program to Illustrate Reversing String Using StringBuilder

package com.masterjavatutorial;

public class ReverseStringUsingStringBuilder {

	public static void main(String[] args) {

		 String str = "HelloWorld";
		 
		 StringBuilder strBuilder = new StringBuilder(str);
		 StringBuilder reversedStr = strBuilder.reverse(); 
		 System.out.println("Reverse of HelloWorld="+reversedStr.toString());
		 
		 String str2 = "How are You?";
		 StringBuilder strBuilder1 = new StringBuilder(str2);
		 StringBuilder reversedStr1 = strBuilder1.reverse(); 
		 System.out.println("Reverse of How are You?="+reversedStr1.toString());

	}

}

Output of the above method is as below:

Reverse of HelloWorld=dlroWolleH
Reverse of How are You?=?uoY era woH

To know more about String , Click Here