I've created a class called Test
that has a constructor and one instance variable String name
:
class Test {
String name;
Test(String name){
this.name = name;
}
}
I instantiate it like this:
Test first = new Test("First");
Test second = first;
first.name = "Change First";
System.out.println("First: " + first.name);
System.out.println("Second: " + second.name);
... and predictably get this:
First: Change First
Second: Change First
This makes sense to me. I'm assigning the second Object to the same memory location referenced in the first - when I change the first, the second changes and vice versa.
Take this:
String x = new String("Hello");
String y = x;
x = new String("Change");
System.out.println("x: " + x);
System.out.println("y: " + y);
The above gives the output:
x: Change
y: Hello
Why is this? They're both extend the Object
class, so why do they behave so differently? Do any other Object
derivatives behave like this?
2 Answers 2
Change your code to:
Test first = new Test("First");
Test second = first;
first = new Test("First");
first.name = "Change First";
System.out.println("First: " + first.name);
System.out.println("Second: " + second.name);
And you'll get:
First: Change First
Second: First
It's got nothing to do with it being a string versus an object. You are changing which object x
points to with x = new String("Change");
, rather than changing the contents of the original object. With first.name = "Change First";
you aren't changing which object it points to; you are changing the contents of the object.
As strings are immutable in Java, you cannot change their contents; you will always be changing the reference instead.
I'm assigning the second Object to the same memory location referenced in the first
There is no "second object." first
and second
are not objects. They are object references. Your program created an object when it called new Test("First")
, and it stored a reference to that object in the first
variable. Then it copied the value of the first
variable (i.e., it copied the reference) to the second
variable.
At that point, each of the two variables refers to the same object, and when your program executed first.name = "Change First";
, it modified that one and only object.
[so, explain this...]
String x = new String("Hello");
String y = x;
x = new String("Change");
System.out.println("x: " + x);
System.out.println("y: " + y);
Your second example creates two objects. It created the first when it called new String("Hello")
. Then it created another when it called new String("Change")
.
Once again, x
and y
are not String
objects. They are object references. Your second example leaves x
holding a reference to the second String
that it created, and it leaves y
holding a reference to the first one.