Java String Reverse using StringBuffer Example

In this example we shall show you how to reverse the string object by using the Java StringBuffer class. StringBuffer class has a method reverse() which is convenient for reversing a given string value. As it is define in the specification:

Causes this character sequence to be replaced by the reverse of the sequence. If there are any surrogate pairs included in the sequence, these are treated as single characters for the reverse operation. Thus, the order of the high-low surrogates is never reversed. Let n be the character length of this character sequence (not the length in char values) just prior to execution of the reverse method. Then the character at index k in the new character sequence is equal to the character at index n-k-1 in the old character sequence.

StringBufferReverseExample.java

package javabeat.net.core;

/**
 * StringBuffer reverse() method example
 * @author krishna
 *
 */
public class StringBufferReverseExample {
	public static void main(String args[]){
		StringBuffer buffer = new StringBuffer();
		buffer.append("JavaBeat");
		System.out.println("JavaBeat is reversed to :" +  buffer.reverse());
	}
}

Output…

JavaBeat is reversed to :taeBavaJ

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*