you cant. string is immutable.
i'll explain what goes on, line by line. it will help to think of java objects as some object, like a ball. it will help to think of the named variable you give as being like a piece of paper tied to the object with string.. a tag, that you have a hold of
now, yu make a new string, and somewhere in memory comes the word "1", tied to it is a label tag, mystr:
mystr-------("1")
you call a method with it, passing in the label. now, your method has the parameter named as String str.. and just like String myStr, this also attaches a label to our object in memory.. note it attaches to the object, NOT your tag:
mystr-------("1")--------str
not:
str------mystr------("1")
not that it would matter but.. you need to be clear that one object now has 2 labels (see above above)
then you make a new object and reattach the str tag to the new:
Code:
mystr--------("1") str------("2")
then the method ends, str goes out of scope and the label is destroyed:
Code:
mystr--------("1") ("2")
the new string "2" is now orphaned and will be garbage collected; it's dead
and mystr is still attached to "1"
this cannot be violated.. string cannot be changed once created..
only a method that works on the object will show a change. as soon as you use the "new" keyword, you are not changing the object; youre making another