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
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With