Monday, November 21, 2005

Java: String & String Buffer usage.

While performing any string manipulations like searching for a character in a string and replacing by a given character, our natural choice would be to use String. But, this is not advisable.

This is because when we make any modification to the existing string, a new string object is created by the JVM. Hence for making four replacement in a string, four new string object would be created and hence a total of five string object would be present in place of one string object. So the better option is to use String Buffer. String buffer doesn't create new objects, instead makes the modification in the original string. Hence string buffer are more space efficient than string.

Strings in Java are stored in "String Buffer pool" maintained by JVM. This is the region each time a new string gets created. The string buffer is created and manuplated in the Heap like any other object.

Example:

{
String strFirstName, strLastName;
strFirstName = "Rakesh";
strFirstName = "Sharma";
strLastName = "Rakesh";
}

What happens in the String Buffer pool is, strFirstName will point to a location contaning the value "Rakesh". Then it points to a new location contaning "Sharma". when strLastName is assigned a value "Rakesh", no new memory location is created for storing instead it points to "Rakesh" which was created earlier.

1 comment:

  1. StringBuffer is also used internally by Java for implementation of + operator for String concatenation. Also StringBuffer methods are synchronized as explained at How StringBuffer works in Java

    ReplyDelete