AA AA BB BB
s1= AA s2 = BB
if everything in java is pass by value and when i passed s1 as argument then the reference of s1 gets copied as s1 stores the reference of string.
As i am doing s1=s1+" "+s1 then it should have changed the original string but it is not....
but let me clarify what i am trying to say:
Since String is a class therefore In this String s1="Hello"
s1 contains reference to the object.
Now if i pass s1 to a function for e.g
func1(s1) //calling func1
void func1(String xyz)
then xyz gets copy of whatever s1 contains.
and s1 contains reference to the object having "Hello"
then if i make changes in the object through xyz then it must reflect in the original object when accessed from s1.
But it is not showing up that....
Jatin sachdev wrote:As i am doing s1=s1+" "+s1 then it should have changed the original string but it is not....
Why should it have changed the original String? Strings are immutable and cannot be changed. What you're doing in that method is creating new Strings that you assign to the local parameter variables s1 and s2. Afterwards, these two no longer refer to the original Strings but to the new Strings. The original Strings, with references in the original s1 and s2 local variables of the main method, remain as they were.
If you use StringBuilder instead of String, this allows you to modify the actual object instead of only the reference. It will then work as you expected:
Jatin sachdev wrote:
Note that you should never create String objects like this. It's unnecessary to create a new String object from a string literal. Just do this:
Strings are immutable. Their state cannot be modified.
Jatin sachdev wrote:then if i make changes in the object through xyz then it must reflect in the original object when accessed from s1
While this is a true statement, it does not apply here.
When you do this:
you create (several) brand new String objects, each with their own memory address. One of these new ones then gets assigned to s1, but the original is not ever changed.