Graphs of equality and memory of objects and strings

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

Let's pretend that:

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

The memory diagram for these two steps is as follows:

  • x-> "Test"
  • x-> "Test" <-y
  • x-> "Test" y-> "Not Test"

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

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

Here, if we change b.var, a.var will also change to 5. Why is this different from the above case by lines?

Also, I would appreciate it if someone did not mind explaining these memory diagrams for strings and objects. Will the result be different if a and b are objects of different classes equal? Thank you

+4
source share
3

b.var = 5;

b = new A();

, , y = "Not Test"; y .

, a, b, .

, :

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

a.var b.var 5, .

+2

String , . A , , . -, A, b , , String, String A b Test A Test1 Test Test1, String Test1 A.

+2

In the second case, they both indicate the same place in memory.

A a = new A();     a-->[MEMORY SPOT NR1]
A b = a;           a-->[MEMORY SPOT NR1] AND b-->[MEMORY SPOT NR1]
b.var = 5;         a-->[MEMORY SPOT NR1] AND b-->[MEMORY SPOT NR1] 
                   and the value in var in [MEMORY SPOT NR1] is 5, 
                   so both a.var and b.var take the value 5
+1
source

Source: https://habr.com/ru/post/1620320/


All Articles