View RSS Feed

My Java Tips

StringBuilder

Rate this Entry
by , 10-30-2011 at 06:32 PM (893 Views)
Java 5 introduces StringBuilder which implements Serializable and CharSequence interfaces. It represents a mutable sequence of characters.


StringBuilder is an API compatible with StringBuffer, but with no guarantee of synchronization. Following are the available constructors:


Java Code:
StringBuilder()
StringBuilder(CharSequence seq)
StringBuilder(int capacity)
StringBuilder(String str)
This can be used in place of StringBuffer where the string buffer was being used by a single thread. Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

StringBuilder provides methods to perform append and insert operations and these methods are overloaded so as to accept data of any type.


These methods effectively converts a given datum to a string and then appends or inserts the characters of that string to the string builder. The append method always adds these characters at the end of the builder; the insert method adds the characters at a specified point.

Following append methods are provided:

Java Code:
StringBuilder append(boolean b)
StringBuilder append(char c)
StringBuilder append(char[] str)
StringBuilder append(char[] str, int offset, int len)
StringBuilder append(CharSequence s)
StringBuilder append(CharSequence s, int start, int end)
StringBuilder append(double d)
StringBuilder append(float f)
StringBuilder append(int i)
StringBuilder append(long lng)
StringBuilder append(Object obj)
StringBuilder append(String str)
StringBuilder append(StringBuffer sb)
Following are the insert methods provided. Use the one that fits your need:



Java Code:
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int dstOffset, CharSequence s)
StringBuilder insert(int dstOffset, CharSequence s, int start, int end)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long l)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String str)
By now you have gone through the list of insert and append methods provided. Letís take an example for better understanding. For example, if obj refers to a string builder object whose current contents are "start", then the method call obj.append("le") would cause the string builder to contain "startle", whereas obj.insert(4, "le") would alter the string builder to contain "starlet".

Submit "StringBuilder" to Facebook Submit "StringBuilder" to Digg Submit "StringBuilder" to del.icio.us Submit "StringBuilder" to StumbleUpon Submit "StringBuilder" to Google

Tags: None Add / Edit Tags
Categories
Java SE

Comments