0

I've looked lotsa websides but i could not find my answer. My question is Why refrence p's values also changed? Even if i did not changed those? Here is my code and thak yu for explanation.

public static void main(String[] args) {

    Person p = new Person();
    Person q = new Person();
    p.name="Sara";
    p.birthyear= 1989;

    q=p;
    System.out.println("Name is "+q.name+" and birthyear is "+q.birthyear);

    q.name ="Hanna";
    q.birthyear = 1991;

    System.out.println("Name is "+p.name+" and birthyear is "+p.birthyear);
}

}

class Person { 
String name;
String surname;
int birthyear;

}

  • 2
    `p` and `q` don't have values themselves, they point to an object that has values. And they point to the same after you do `q=p`. After that, you access that same object via both `p.` and `q.` – zapl Jun 16 '16 at 16:20
  • I've searched and read lot of things on internet about my question and if i understood correctly. The assignment changes the refrence variabel q(It means q's pointer and p's pointer shows the same memory space(heap) ). I mean q's pointer and p's pointer shows the same object that's why when i'm changing q's values i'm changing p values too. – Lena Monika Marshall Jun 16 '16 at 19:40
  • 1
    Correct, both p and q contain an address of an object that exists on the heap, `q=p` copies the address value from p to q so they both point to the same. – zapl Jun 16 '16 at 22:07

0 Answers0