Nil. Hatamova wrote:Why in the second code s1 does not change but in the first code it changes?
1.output is one two three 2.output is one two one three
But i thought output for second code will be "one two one two three";
The thing you are missing is in the second code, when s1 is passed to alter method it is treated as a local method reference variable referring to "one" , once the alter methods changes the s1 like s1 = s1 + "two" , s1 start referring to a different object on heap whereas the original s1 string remain unchanged still referring to "one"and that's why its result in this one two one three. Hope you understand.
Java uses pass by value, a copy of the reference is passed to the alter() method. And the above line creates a new string object with contents "one two", that the copy of the reference now points to. But the original reference in the start method still points to "one" and hence the output "one two one three".