Wednesday, 1 February 2012

String and StringBuffer

Immutability of String objects


As you know, Strings are objects in Java code. These objects, however, are immutable. That is, their value, once assigned, can never be changed. For instance:

String msg = "Hello";
msg += " World";


Here the original String "Hello" is not changed. Instead, a new String is created with the value "Hello World" and assigned to the variable msg. It is important to note that though the String object is immutable, the reference variable is not.

String literals


In Java code, the String literals are kept in a memory pool for efficient use.

If you construct two Strings using the same String literal without the new keyword, then only one String object is created. For instance:

String s1 = "hello";
String s2 = "hello";


Here, both s1 and s2 point to the same String object in memory. As we said above, String objects are immutable. So if we attempt to modify s1, a new modified String is created. The original String referred to by s2, however, remains unchanged.

StringBuffer


StringBuffer objects are mutable, which means their contents can be changed. For instance:

Stringbuffer s = new StringBuffer("123");
s.append("456");     // Now s contains "123456"


You can see how this differs from the String object:

String s = new String("123");
s.concat("456");      // Here s contains "123"

No comments:

Post a Comment