-2
class Main {
  public static void main(String[] args) {
     String s1 = "xy";
     String s2 = s1;
     s1 = s1 + s2 + "z";
     System.out.println(s1);
     System.out.println(s2);
  }
}

When I ran the code i was expecting to get something like this, because the value of s1=s2 :

xyxyz
xyxyz

But the actual output is:

xyxyz
xy

I am unsure why i don't get the same answer? Is it because the line of code changing s1 to the value "xyxyz" was ran after making s1=s2?

Mikez8
  • 1
  • 1
  • 1
    What do you think `s1=s2;` does? To answer that question you may need to know [What is the difference between a variable, object, and reference?](https://stackoverflow.com/q/32010172) – Pshemo Sep 12 '19 at 23:06

3 Answers3

1

Java Strings are immutable. When you reassign s1, you create a new String which s1 now references. s2 is still referencing the original string.

kingkupps
  • 3,284
  • 2
  • 16
  • 28
0

Essentially when you do s1 = s2, you are not tying the two into one object, but rather that their values are the same for the time being (this is somewhat simplified). If you were to change the values of either one, it would not affect the values of the other.

Imagine having a .txt file. You type whatever you want to type in it, and then copy and paste it. Afterwards, you go back in the original file and continue typing. The text in the duplicate file hasn't changed, although the text in the original has. This is mostly comparable to what is happening here.

Joshua Burt
  • 76
  • 1
  • 7
0

String s2 = s1; is an assignment, not a designation of eternal equality.

That line means, “when the program executes this line, set the value of the s2 variable to be the same as the value the s1 variable contains at the moment it executes.”

Any later changes to the variable s1 will not affect s2. The assignment was a momentary transfer of information, nothing more.

VGR
  • 40,506
  • 4
  • 48
  • 63