Pass-by-value
Java is pass-by-value (see Is Java “pass-by-reference” or “pass-by-value”?).
Which means that when you do
Person first = new Person("John");
Person second = first;
you have two different variables, both pointing to the instance new Person("John")
in memory. But again, both variables are different:
first ---|
|---> new Person("John")
second ---|
If you manipulate the object itself the change is reflected to both variables:
second.setName("Jane");
System.out.println(first.getName()); // Jane
The diagram is now:
first ---|
|---> new Person("John").setName("Jane")
second ---|
But if you change where a variable points to, it obviously does not affect the other variable since you didn't touch the object they point to:
second = new Person("Jane");
System.out.println(first.getName()); // John
After that statement you have two variables pointing to different objects:
first ---> new Person("John")
second ---> new Person("Jane")
Explanation
Let's transfer that knowledge to your code. You wrote:
String g = x_map.get(42);
g = "bar";
and are asking why g = "bar"
did not affect what the map stores.
As said, you only change where the variable g
is pointing to. You don't manipulate the object inside the map. The diagram is first:
|---> x_map.get(42)
g ---|
"bar"
and then
x_map.get(42)
g ---|
|---> "bar"
Solution
If you want to change the object, you would need to manipulate it directly instead of only changing the variable reference. Like first.setName("Jane")
. However, in Java String
s are immutable. Meaning that there is no way of manipulating a String
. Methods like String#replace
don't manipulate the original string, they always create a new String
object and leave the old one unchanged.
So in order to change what the map stores for they key 42
you just use the Map#put
method:
x_map.put(42, "bar");
This will change what x_map
stores for the key 42
to "bar"
.