Jony
Jony

Reputation: 6774

Java reference type

How does Java deal with passing reference data type arguments?? Can somebody give a clear picture?

Upvotes: 3

Views: 3189

Answers (2)

Adam Batkin
Adam Batkin

Reputation: 52994

All Java objects (everything except primitives such as int, float, boolean, etc...) are references to the pointed-to-object.

So for example:

Foo f = new Foo();

Above, f is a reference to an object of type Foo. If you then have a function:

void doSomething(Foo myFoo) { ... }

doSomething(f);

The doSomething() function receives the same object that f refers to. So if doSomething() mutates f, it is mutating that object.

Unlike C++, there is no choice between passing by value, reference or using pointers: All class-type variables are references (or pointer depending on your exact terminology).

One problem here is that people often try to apply their C++ knowledge and terminology to Java, which won't work.

Upvotes: 1

Andrew Hare
Andrew Hare

Reputation: 351496

Java passes a copy of the reference to the method. The reference still points to the same instance.

Imagine if I had a slip of paper with a restaurant's address on it. You also want to go to the same restaurant so I get a new slip of paper and copy the address of the restaurant on to that paper and give it to you. Both slips of paper point to the same restaurant but they are separate references to the instance.

The restaurant itself is not duplicated, only the reference to it is duplicated.

Jon Skeet provides a similar analogy:

The balloon analogy

I imagine every object as a helium balloon, every reference as a piece of string, and every variable as something which can hold onto a piece of string. If the reference is a null reference, that's like having a piece of string without anything attached to the end. If it's a reference to a genuine object, it's a piece of string tied onto the balloon representing that object. When a reference is copied (either for variable assignment or as part of a method call) it's as if another piece of string is created attached to whatever the first piece of string is attached to. The actual piece of string the variable (if any) is holding onto doesn't go anywhere - it's only copied.

Here is an example:

// Here I have one instance and one reference pointing to it
Object o = new Object();
// At this moment a copy of "o" is made and passed to "foo"
foo(o);

void foo(Object obj) {
    // In here I have obj which is a copy of whatever
    // reference was passed to me
}

Upvotes: 10

Related Questions