Now the details...

The problem we're facing here is statements like

In Java, Objects are passed by reference, and primitives are passed by value.

This is half incorrect. Everyone can easily agree that primitives are passed by value;
there's no such thing in Java as a pointer/reference to a primitive.

However, Objects are not passed by reference.
A correct statement would be Object references are passed by value.

This may seem like splitting hairs, bit it is far from it.
There is a world of difference in meaning.
The following examples should help make the distinction.

In Java, take the case of

public void foo(Dog d) {
d = new Dog("Fifi");
}

Dog aDog = new Dog("Max");
foo(aDog);

the variable passed in (aDog) is not modified!
After calling foo, aDog still points to the "Max" Dog!

Many people mistakenly think/state that something like

  public void foo(Dog d) {
d.setName("Fifi");
}
shows that Java does in fact pass objects by reference.

The mistake they make is in the definition of itself. When you write

  Dog d;

you are defining a pointer to a Dog object, not a Dog object itself.

Calling

  foo(d);

passes the value of d to foo; it does not pass the object that d points to!
The value of the pointer being passed is similar to a memory address.

The use of the word "reference" in Java was an incredibly poor choice (in my not-so-humble opinion...) Java has pointers, plain and simple. The designers of Java wanted to try to make a distinction between C/C++ pointers and Java pointers, so they picked another term. Under the covers, pointers are implemented very differently in Java and C/C++, and Java protects the pointer values, disallowing operations such as pointer arithmetic and invalid runtime casting.

However, it makes no difference how pointers are implemented under the covers. You program with them exactly the same way in Java as you would in C or C++.

In Java,

  Dog d;   // Java

is exactly like C or C++'s

  Dog *d;  // C++

And using

  d.setName("Fifi");  // Java

is exactly like C++'s

  d->setName("Fifi"); // C++

To sum up: Java has pointers, and the value of the pointer is passed in. There's no way to actually pass an object itself as a parameter. You can only pass a pointer to an object.

Keep in mind, when you call

  foo(d);

you're not passing an object; you're passing a pointer to the object.

Comments

Popular posts from this blog

BIP Formatting

Repeat Table Header in all pages in BIP

Limit rows per page