Wednesday, 9 November 2016

Difference between String, StringBuffer and StringBuilder


The String class represents character strings. All string literals in Java programs, such as "xyz", are implemented as instances of String class.
Strings are constant, i.e. their values cannot be changed after they are created.
String objects are immutable and they can be shared.

For example:

     String str = "xyz";

is equivalent to:

     char data[] = {'x', 'y', 'z'};
     String str = new String(data);

The class String includes methods for
  • Examining individual characters of the sequence
  • Comparing strings
  • Searching strings
  • Extracting substrings
  • Creating a copy of a string with all characters translated to uppercase or to lowercase.

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings.
String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method.

String conversions are implemented through  toString method, which is defined in  Object class.


StringBuffer is a thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
String buffers are safe for use by multiple threads. The methods of StringBuffer are synchronized.

The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type.
Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer.
The append method always adds these characters at the end of the buffer
The insert method adds the characters at a specified point.

For example,
if str refers to a string buffer object whose current contents are "pot",
then the method call z.append("s") would cause the string buffer to contain "pots",
whereas z.insert(2, "s") would alter the string buffer to contain "post".

If sb refers to an instance of a StringBuffer, then sb.append(x) has the same effect as sb.insert(sb.length(), x).


Since Java 1.5
StringBuilder is a  mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization.
This class is designed for use as a drop-in replacement for StringBuffer in places 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.

Instances of StringBuilder are not safe for use by multiple threads. If such synchronization is required then it is recommended that StringBuffer be used.

1 comment:

Related Posts Plugin for WordPress, Blogger...