mickey
mickey

Reputation: 413

How does Java dereferencing work?

I need to get some clarification on Java references (pointers). I have read this (Java is Pass-by-Value, Dammit! by Scott Stanchfield) excellent write up on Java's way of passing variables around. As far as I understand everything is passed around as memory pointers.

public class foo{
    int a;
    int b;

    public foo(a, b){
       this.a = a;
       this.b = b;
    }
}

so in some code like this:

foo aFoo = new foo(1,2); //new foo created at adress 0x40 for instance
someFunc(aFoo);

the argument to someFuncis actually the number 0x40 (albeit this might be a simplification, but to get a sense for the pattern).

Now, suppose i created another class

public class bar{
    foo aFoo;

    public bar(){
       this.aFoo = new foo(1,2);
    }
}

and instantiated the following variables

bar aBar = new bar();
foo bFoo = new foo(3,4);

now suppose i want to copy the values of aBar.aFoo into bFoo like

bFoo = aBar.aFoo;

If i now do

bFoo.a = 1234;

did i also just change aBar.aFoo.a into 1234 or does that variable still hold the value 1?

By my own logic, bFoo.a is just a pointer, so assigning a new variable should alter both places, but this seems incorrect. So I guess i have not fully understood Java's "reference is really a pointer" concept. Or rather, i might understand the pointer part of it, but not the dereferencing of the pointers, since this is done implicitly compared to in C where you always know.

Upvotes: 2

Views: 5050

Answers (1)

Marko Topolnik
Marko Topolnik

Reputation: 200138

bFoo = aBar.aFoo;

-> you have assigned the aBar.aFoo reference to bFoo local variable. This is called aliasing because now you have two ways to refer to the same object: bFoo and aBar.aFoo.

bFoo.a = 1234;

-> you have assigned 1234 to the a field of the object referred to by bFoo. This object is referred to by aBar.aFoo as well.

Result: you have changed the value of aBar.aFoo.a.

Upvotes: 5

Related Questions