Forgive me if this is a duplicate, I can't seem to find anything that explains what I'm seeing well.
The following program:
Object a = new Object();
Object b = a;
System.out.println( "a: " + a );
System.out.println( "b: " + b );
a = null;
System.out.println( "a: " + a );
System.out.println( "b: " + b );
Yields this:
a: java.lang.Object@3e25a5
b: java.lang.Object@3e25a5
a: null
b: java.lang.Object@3e25a5
But WHY?!? I'm so confused by this. Shouldn't "b" be referencing "a"? Therefore, if "a" no longer references anything else (eg: null) then shouldn't "b"? I'm obviously missing something fundamental here.
Thanks in advance.
EDIT #1
I think what threw me off was I am printing out the address. For some reason, in my mind, I was printing out some magic value indicating the pointers\references - when in reality setting b = a
is not making them the same, it is simply creating a new pointer to the same place on the heap. I hope this helps someone else.
b
is not referencing a
it referencing to the same object a
is referencing to when the assignment was performed.
I know this is not same language but if you are familiar with C, it is like:
int someNum = 5;
int * a = &someNum; // a points to someNum
int * b = a; // b points to someNum too
a = NULL; // a doesn't point to anything (points to address 0), b still points to someNum
(I used C as it gives a clearer look of addresses and references)
Lets take a detailed look at what is happening:
//A is pointing to a new Object lets assume memory location for 1 for simplicity
Object a = new Object();
//B is now also pointing to memory location 1
Object b = a;
//Both print the same they are both pointing to memory location 1
System.out.println( "a: " + a );
System.out.println( "b: " + b );
//a is now pointing to null, but there is no change to b which is still pointing to memory location 1
a = null;
System.out.println( "a: " + a );
System.out.println( "b: " + b );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With