Java: StringBuilder reverse() method

In this article, we will discuss StringBuilder’s reverse() method which is used to reverse the contents of invoking StringBuilder object

 

reverse() method:

  • This StringBuilder method is used to reverse the sequence of character of the invoking StringBuilder object
  • Note: sometimes it is used to convert string in reverse order

Method Signature:

public StringBuilder replace(int start, int end, String str);

Returns:

  • Returns StringBuilder object with reversed contents (or say in reverse order)

 

Examples on reverse() method:

To reverse StringBuilder contents

StringBuilderReverseMethod.java

package in.bench.resources.stringbuilder.methods;

public class StringBuilderReverseMethod {

	public static void main(String[] args) {

		// StringBuilder - 1
		StringBuilder sb1 = new StringBuilder("Pune SuperGiants");
		System.out.println("1.A StringBuilder "
				+ "original contents : " + sb1);

		// to reverse StringBuilder contents
		sb1.reverse();
		System.out.println("1.B StringBuilder "
				+ "reverse contents  : " + sb1);


		// StringBuilder - 2
		StringBuilder sb2 = new StringBuilder();
		sb2.append("Netherlands"); // append string
		System.out.println("\n\n2.A StringBuilder "
				+ "original contents : " + sb2);

		// to reverse StringBuilder contents
		sb2.reverse();
		System.out.println("2.B StringBuilder "
				+ "reverse contents  : " + sb2);
	}
}

Output:

1.A StringBuilder original contents : Pune SuperGiants
1.B StringBuilder reverse contents  : stnaiGrepuS enuP


2.A StringBuilder original contents : Netherlands
2.B StringBuilder reverse contents  : sdnalrehteN

 

References:

 

Happy Coding !!
Happy Learning !!

Java: StringBuilder substring() method
Java: StringBuilder replace() method