• Post Reply Bookmark Topic Watch Topic
  • New Topic

String Immutability  RSS feed

Basu Patel
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As we all know that Strings are immutable and can not be modified unless one creates a new instance object with the modified changes, but with the reference to StringBuffers can we say that strings are mutable ? ie, whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the following String methods, which will construct a new copy of the String with your modifications complete.
subString() - You can extract a substring using subString()
String substring(int startindex)
String substring(int startIndex,int endIndex)
concat() - You can concatenate 2 strings using concat(),shown here:
String concat(String str)
replace() - this method replaces all the occurences of one string with another character.
String replace(char original,char replacement)
trim() - this method returns a copy of the invoking string from which any leading and trailing
whitespaces has been removed.
String trim()
append() - method concatenates the string representation of any other type of data to the end
of the invoking StringBuffer object.(refer pg 367)
Insert() - method inserts one string into another.(refer pg 368)
reverse() - method reverses the characters within a StringBuffer object
StringBuffer reverse()
delete() and deleteCharAt() - Java 2 adds to StringBuffer the ability to delete characters using the
these methods.
StringBuffer delete(int startIndex,int endIndex)
StringBuffer deleteCharAt(int loc)

Thanx for you time!
Sachin Kombrabail
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
When we say that Strings are immutable, we mean the String object. The moment you copy the contents of a string object into a StringBuffer, it is a different object altogether. Nobody said that StringBuffers are immutable. So we can do anything with StringBuffer objects , but not String object.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!