Search code examples
javaobjectpseudocode

How come the object "person1" and the object "person2" are the same?


In this program, whenever you change person1 or person 3, they become contain the same values. I tried going through each step in pseudo code, but I get lost on the reasoning behind these two objects always being equal. Could you help explain these steps? I would really love to understand. Thank you for your time.

public class References1
{
    public static void main (String[] args)
    {
        Person person1 = new Person ("Rachel", 6);
        Person person2 = new Person ("Elly", 4);
        Person person3 = new Person ("Sarah", 19);

        System.out.println ("\nThe three original people...");
        System.out.println (person1 + ", " + person2 + ", " + person3);

        // Reassign people
        person1 = person2;
        person2 = person3;
        person3 = person1;


        System.out.println("\nThe three people reassigned...");
        System.out.println (person1 + ", " + person2 + ", " + person3);

        System.out.println();
        System.out.println ("Changing the second name to Bozo...");
        person2.changeName ("Bozo");
        System.out.println (person1 + ", " + person2 + ", " + person3);

        System.out.println();
        System.out.println ("Changing the third name to Clarabelle...");

        person3.changeName ("Clarabelle");
        System.out.println (person1 + ", " + person2 + ", " + person3);
        System.out.println();
        System.out.println ("Changing the first name to Harpo...");
        person1.changeName("Harpo");
        System.out.println (person1 + ", " + person2 + ", " + person3);
    }
}

Solution

  • These are the lines causing your problem:

    // Reassign people
    person1 = person2;
    person2 = person3;
    person3 = person1;
    

    If the variables had the following starting values:

    person1 = "A";
    person2 = "B";
    person3 = "C";
    

    ... and then you ran it through your code:

    person1 = person2 -> person1 is now set to "B" (the value "A" is discarded)
    
    person2 = person3 -> person2 is now set to "C"
    
    person3 = person1 -> person3 is now set to the value of person1 which is "B"
    

    So now variable person1 and person3 are set to the same object.