I would like to make a copy of a string and then have the ability to make changes to the copy without changing the whole string. I tried using
String strTemplateTemp=new String(strTemplate);
instead of
String strTemplateTemp=strTemplate;
I also tried using clone
but got an error saying the clone method was not visible: String strTemplateTemp=strTemplate.clone();
My code
DefaultListModel<String> getAllMacrows()
{
DefaultListModel<String> rows= new DefaultListModel<String>();
int pes=0;
int nameStart;
int parEnd;
String row;
String strTemplateTemp=new String(strTemplate);
strTemplateTemp=strTemplateTemp.replace("\n"," ");
// now both strTemplateTemp and strTemplate have chnaged
// want just strTemplateTemp to chnage
In Java String
instances are immutable, so it is not possible to change the string (i.e., have a side effect). The statement:
strTemplateTemp=strTemplateTemp.replace("\n"," ");
Creates a new string and assigns a reference to the new string to the variable strTemplateTemp
.
Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. java.lang.String
See this post for details.