Search code examples
javastringobjectequality

Objects and Strings equality and memory digrams


I have having a bit of trouble understanding the difference between these two:

Suppose we have:

 String x = "Test";
 String y = x;
 y = "Not Test"; //x is not modified here

The memory diagram for these two steps is the following:

  1. x-> "Test"
  2. x-> "Test" <-y
  3. x-> "Test" y-> "Not Test"

But, consider class A with field 'int var':

A a = new A();
A b = a;
b.var = 5; 

Here, if we modify b.var, a.var also changes to 5. Why is this different from the above case with strings?

Additionally, I would appreciate it if someone wouldn't mind explaining these memory diagrams for strings and objects. Would the result be different if a and b were objects of different classes set equal? Thanks.


Solution

  • There's a difference between

    b.var = 5;
    

    and

    b = new A();
    

    The second statement is similar to what you do in your first snippet, since y = "Not Test"; makes y refer to a new instance.

    The first statement updates the state of the instance referred by both a and b, so both are affected.

    Here's a diagram that shows your second snippet :

    a -> object of class A <- b
         containing an int
         variable `var`
            var <- 5
    

    Both a.var and b.var contain 5, since they are the same variable.