Reputation: 179
I understand that classes are reference types, for example I created the following class:
class Class {
String s = "Hello";
public void change() {
s = "Bye";
} }
With the following code, I understand that Class
is a reference type:
Class c1 = new Class();
Class c2 = c1; //now has the same reference as c1
System.out.println(c1.s); //prints Hello
System.out.println(c2.s); //prints Hello
c2.change(); //changes s to Bye
System.out.println(c1.s); //prints Bye
System.out.println(c2.s); //prints Bye
Now I want to do the same thing with a String, that doesn't work. What am I doing wrong here?:
String s1 = "Hello";
String s2 = s1; //now has the same reference as s1 right?
System.out.println(s1); //prints Hello
System.out.println(s2); //prints Hello
s2 = "Bye"; //now changes s2 (so s1 as well because of the same reference?) to Bye
System.out.println(s1); //prints Hello (why isn't it changed to Bye?)
System.out.println(s2); //prints Bye
Upvotes: 12
Views: 6859
Reputation: 1
Java is pass-by-value. If you are passing an object into method then you are accualy passing only value of this object, not the object itself and it's value remains the same
Upvotes: -2
Reputation: 3894
This is because you are updating the reference of s2 and not s1. Lets see how your code got executed:
String s1 = "Hello";
String s2 = s1;
A Hello
literal string created in String pool
, whose reference was then put to s1
. Then in the second line s2
also got the same reference.
By now, s1
and s2
are pointing to the same literal string in String pool
.
Now when the below piece of code got executed.
Another, literal Bye
got created in String pool
and the reference was put in s2
. Howoever, s1
still has the old reference and hence is printing Hello
.
Upvotes: 7
Reputation: 7638
In the first case you are calling a method to the referenced object, thus the referenced object changes, not the 2 references:
In the second case you are assigning a new object to the reference itself, which is then pointing to that new object:
Upvotes: 22
Reputation: 1
String s1="Hello"; String s2=s1;
When you do the change like,
s2="Bye";
you are doing this
s2 = new String("Bye");
explicitly.
Upvotes: -3
Reputation: 17890
s2 = "Bye";
This is equivalent to creating a new String object and assigning its reference to s2
(s2 = new String("Bye");
) and hence s1
and s2
are different.
You are comparing the above with a method call like c2.change()
which changes some internal field value.
In other words, s2 = "Bye";
is equivalent to Class c2 = new Class();
in your example. After c1.change()
, you cannot expect, c1
and c2
to have the same value for field s
.
Upvotes: 0