Java: StringBuffer reverse() method

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

 

reverse() method:

  • This StringBuffer method is used to reverse the sequence of character of the invoking StringBuffer object
  • Note: sometimes it is used to convert string in reverse-order
  • But that String need to be converted to StringBuffer using append() method
  • and later when reversing is done, again converting StringBuffer to String

Method Signature:

public StringBuffer reverse();

Returns:

  • Return the StringBuffer object with reversed contents (or say in reverse-order)

 

Examples on reverse() method:

  • To reverse StringBuffer contents

StringBufferReverseMethod.java

package in.bench.resources.stringbuffer.methods;

public class StringBufferReverseMethod {

	public static void main(String[] args) {

		// StringBuffer - 1
		StringBuffer sb1 = new StringBuffer("Mumbai Indians");

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


		// StringBuffer - 2
		StringBuffer sb2 = new StringBuffer();
		sb2.append("Made in India"); // append string

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

Output:

1. StringBuffer reverse contents : snaidnI iabmuM
2. StringBuffer reverse contents : aidnI ni edaM

 

References:

 

Happy Coding !!
Happy Learning !!

Java: StringBuffer substring() method
Java: StringBuffer replace() method