Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java null reference copying

Tags:

java

reference

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.

like image 259
javamonkey79 Avatar asked Jul 23 '11 17:07

javamonkey79


2 Answers

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)

like image 69
MByD Avatar answered Oct 04 '22 19:10

MByD


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 );
like image 27
Oscar Gomez Avatar answered Oct 04 '22 18:10

Oscar Gomez