Witscale Test Center

13.4 The java.lang.StringBuffer class > 13.4.1 StringBuffer objects are mutable (changeable).


13.4.1 StringBuffer objects are mutable (changeable).

Like the String class, the StringBuffer class also represents the strings (sequence) of characters in Java. And similar to the String objects, the StringBuffer objects also use 16-bit Unicode to represent characters. But the major difference between a String object and a StringBuffer object is that the StringBuffer object is mutable. It means that the content with which it is created initially can be changed without any problem. You can create a StringBuffer object by passing a string to its constructor as:

 

StringBuffer buffer = new StringBuffer(“Hello”);

 

We saw earlier that if we call the concat() method on a string object, the string object does not change instead it created a new string object with concatenation. The StringBuffer has an append() method which is similar to concat(). But this method modifies the contents of the same StringBuffer object. The table shows the difference in the way these two type of objects handle string manipulation.

 

Table 13.2 Comparing the string manipulation with String and StringBuffer Object

 

 

Concatenating a string

Appending to a string Buffer

Source code

String msg = new String("Hello");

msg = msg.concat(" World!");

System.out.println(msg);

StringBuffer msgBuf = new StringBuffer("Hello");

msgBuf.append(" World!");

System.out.println(msgBuf);

Output

Hello World!

Hello World!

 

Even if we got the same result by using string object and string buffer, the string object approach has a downside. The original String “Hello” is lost in the String pool wasting the memory. However, when you use a StringBuffer instead of a String, the StringBuffer object initially contains “Hello”. The same object is then modified to append “ World!” as well. It does not go on creating new StringBuffer objects. Table 13.3 shows the difference with the help of memory model for both approaches.

 

Table 13.3 String manipulation with a String and StringBuffer

 

Concatenating a string

Appending to a string Buffer





 

The memory would have a lost string object after concatenation. But the memory model after appending to StringBuffer object does not show any lost object because only one StringBuffer object is created and being modified through out.