I learned that when you modify a variable in Java it doesn't change the variable it was based on
int a = new Integer(5);
int b = a;
b = b + b;
System.out.println(a); // 5 as expected
System.out.println(b); // 10 as expected
I assumed a similar thing for objects. Consider this class.
public class SomeObject {
public String text;
public SomeObject(String text) {
this.setText(text);
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
After I tried this code I got confused.
SomeObject s1 = new SomeObject("first");
SomeObject s2 = s1;
s2.setText("second");
System.out.println(s1.getText()); // second as UNexpected
System.out.println(s2.getText()); // second as expected
Please explain to me why changing any of the objects affects the other one. I understand that the value of variable text is stored in the same place in memory for both of the objects.
Why the values for variables are independent but correlated for objects?
Also, how to duplicate SomeObject, if simple assignment does not do the job?