hi, we all are know that String is immutable and StringBuffer is not(mutable).But why String has replace() method?It causes String can be modified by some means.However replace is there for StringBuffer-it is OK!What is actual meaning of immutable? So i need some explanation about it. Can anyone explain?please.
I'm not getting your doubt.. Let me explain something. String s = "java"; s.toLowerCase --- No new object created s.toUpperCase --- new object created s.trim --- No new object created s.replace('j','v') --- new object created String x = "JAVA"; x.toLowerCase --- creates new object x.toUpperCase --- No new object created x.trim --- No new object created
Shi, There is no problem with String having a replace() method. Infact, String can have any kind of method which modify the string (if so required). The only point to note in all these methods is that they produce new objects as their output (there are exceptions - refer the API for that). For StringBuffer, the update methods do not produce a new object. That is the only difference.