9/15/2006

Reverse a String with StringBuilder or StringBuffer

Both StringBuilder and StringBuffer class have a reverse method. They work pretty much the same, except that methods in StringBuilder are not synchronized. This is the signature of StringBuilder.reverse:

public StringBuilder reverse()
This method returns an instance of StringBuilder. The interesting thing is, the returned value is actually itself. So what this method does is, it reverses itself and returns itself. This is the source code for StringBuilder.reverse:
public StringBuilder reverse() {
super.reverse();
return this;
}
In the following example, the old and the reversed string will print the same content after calling reverse method:
public static void main(String[] args) {
StringBuilder old = new StringBuilder(args[0]);
StringBuilder newsb = old.reverse();
System.out.println("original string: " + old);
System.out.println("new string: " + newsb);
}
If you still need to access the original content of the StringBuilder, you will need to save it to string before invoking sb.reverse().

4 comments:

Jack said...

You can also take help of this article..

http://go4knowledgeblog.blogspot.com/2012/05/netbeans-help-create-program-which.html

Subham said...

You have used reverse method of java class StringBuilder , what if we do not need to use built in java method.

Steve Smith said...

Great and Useful Article.

Online Java Training

Java Online Training India

Java Online Course

Java EE course

Java EE training

Best Recommended books for Spring framework

Java Interview Questions








Java Course in Chennai

Java Online Training India

eMexo Technologies said...

Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

Internet Of Things training in electronic city