All Articles

String is immutable, what does it mean ?

this is a basic knowledge but some people don't know about it. in JavaLanguage String is immutable, you can’t modify a String Object but actually replace it by creating a new when u modify the contents. its very expensive when u loop and modify the string. Java will create many String instace and destroy it immediately. its not efficient

String myText = "some text" int loop = 100; 
for(int i =0; i<loop; i++) {
    myText += i;
}
return myText;

The efficient version using StringBuffer / StringBuilder Class. they were added in Java 5. StringBuffer is mutable, so u can modify it.

StringBuffer myText = new StringBuffer(110);
myText.append("Some text");
for(int i =0; i<count; i++) {
    <br /> myText.append(i);
}
return myText.toString();

The above code creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer expands as needed.