a
and b
are references to the same Array (there is a single Array object in memory.)
a ---> ["a", "b", "c"] <---- b
You are changing this array value with this line :
a[0] = "Z"
So you know have this in memory :
a ---> ["Z", "b", "c"] <---- b
For the Strings, it's different.
At first, you have two variables pointing the same value :
String s1 = "hello";
String s2 = s1;
You have this in memory :
s1 ---> "hello" <---- s2
But then, you assign s1 to a new value with this code :
s1 = "world";
The variable s2 still points to the string "hello". There are now 2 string objects in memory.
s1 ---> "world"
s2 ---> "hello"
In Java, Strings are immutable, but arrays are mutable.
See also this question.
Note that if you define a class of yours, the behavior will be closer to the Array.
public class Foo() {
private int _bar = 0;
public void setBar(int bar) {
this._bar = bar
}
public void getBar() {
return this._bar;
}
}
Foo f1 = new Foo();
Foo f1 = f2;
You have this :
f1 ----> Foo [ _bar = 0 ] <---- f2
You can work on the object :
f1.setBar(1)
f2.setBar(2) // This is the same object
This makes something a bit "like" the array :
f1 ----> Foo [ _bar = 2 ] <---- f2
But if you assign f2 to another value, you get this :
f2 = new Foo();
Which creates a new value in memory, but still keeps the first reference
pointing to the first object.
f1 ----> Foo [ _bar = 2 ]
f2 ----> Foo [ _bar = 0 ]