JerryCrowley
JerryCrowley

Reputation: 145

Java Assignments

I'm studying for an exam, and I'm looking through a sample program and I am confused. Here is the code:

public class Problem1 {
public static void f(A X)
{
    A Y = X;
    Y.key = X.key + 1;
}

public static void f(B X)
{
    B Y = new B();
    Y.key = X.key + 2; //Y.key = 12
    X = Y; //X points to Y? 
}

public static void main(String[] args)
{
    A P = new A();
    P.key = 3;
    B Q = new B();
    Q.key = 10;
    f(P);
    System.out.println(P.key);
    f(Q);
    System.out.println(Q.key);
    P = Q;
    f(P);
    System.out.println(P.key);
    }
    }

    class A
    {
public int key;
    }
    class B extends A 
    {

    }

I am fine with f(P). The question I have is with f(Q). I get that a new B named Y is made, and it's key is 12. The question I have is that, shouldn't X = Y point X to Y? Making Q's key value 12 rather than 10? The code prints out 4,10,11. I'm confused as to why it prints 10 rather than 12.

Upvotes: 1

Views: 330

Answers (1)

In java each variable of a class type, like P, Q, X etc, is a reference to an object (or null). You can imagine that there's an object somewhere in memory and the variable points to it:
P -----> (P object)
When you call f(P), the first f method receives a reference to the same object, but it is a different reference:
(main) P -----> (P object)
(f) X -----> (P object)
Then f makes yet another reference:
(f) Y -----> (P object) And when it changes the key, it changes it in the same object.

In the second case, f(Q), the second f method again receives a (different) reference to the same object:
(main) Q -----> (Q object)
(f) X -----> (Q object)
then it makes a new object: (f) Y -----> (Y object)
then it changes the key in this object, and sets the X variable to point to this object:
(f) X -----> (Y object, key=12)
however, in your main method, the Q variable hasn't changed:
(main) Q -----> (Q object)
because X was just a copy of Q, it's not Q itself. So Q still points to the Q object, which was not modified, the Y object was modified.

Upvotes: 3

Related Questions