218 points · by xvirk · 11y ago · 243 comments
"However, Objects are not passed by reference. A correct statement would be Object references are passed by value."
Instead it rants at length to somehow save definitions that are clearly not particularly helpful in a language like Java.
This article just reeks of this certain kind of socially inept, completely unhelpful attitude and technical pedantry that has infected mailinglists and IRC channels over the world. Actively trying to misunderstand people in an effort to expose their ignorance or unfamiliarity with intricacies of whatever language or tool they are trying to navigate.
Its a terrible habit up there with feigned surprise.
The article goes to great length to argue why Java should use the same terminology as other languages. I would not say that the statements:
Sun wanted to push Java as a secure language, and one of Java's advantages was that it does not allow pointer arithmetic as C++ does.
They went so far as to try a different name for the concept, formally calling them "references". A big mistake and it's caused even more confusion in the process.
can be called "actively trying to misunderstand people". In fact it shows an understanding with the position he's arguing against.
If I drove your grandmother BY a car, it would be totally different than driving her AS a car (logically: if your grandmother had wheels, then she'd be a car). In the same sense, passing the value of an object BY reference is totally different than passing a reference to an object AS a value.
Nobody's "actively trying to misunderstand people," because those people are already actively confused and insist on clinging to and spreading their shallow, incorrect definitions that directly contradict the Java language specification itself.
No matter how many times how many people patiently explain it to them in clear unambiguous terms, they still insist they're right and everyone else including the Java spec and James Gosling himself are wrong. Just look at all the ignorant postings in this thread by people like Mark Stock, Mark Hedley and Kevin Ryan, who just can't get it through their heads that they're wrong.
http://www.theserverside.com/discussions/thread.tss?thread_i...
Which is exactly how C does it. I don't see how this is a difficult enough concept to grasp that we need an article explicitly pointing out how Java is just like C in this respect.
As someone who started in Asm, I think pass-by-value/pass-by-reference are also intuitive there in the true "understood without needing any explanation" sense, since basically everything you'd pass to a procedure is a value of some sort, and it only depends on whether you are to interpret that value as a memory address.
And C++ shows actual reference passing.
No, it isn't.
In C, a pointer is a reference. It supports arithmetic, but it works like a reference as well, so the name applies.
What might confuse people is that in C, you do have to specifically ask for a reference to something, whereas in Java, everything which isn't a primitive type is already a reference.
It's true your code can't dereference those references such that it gets access to all of the data in a List object, for example. C works the same way, again: It's entirely possible to say something like 'typedef struct foo mfoo;' and then declare all of your functions to take pointers to type mfoo, and client code will never be able to get its hands on a struct foo object. FILE pointers work just like this, for example.
Because that particular argument used to be a thing.
In my experience, imprecise semantics and the misunderstandings that arise from them are a/the major cause of error, in both the requirements and implementation domains.
C has the address-of operator (&). So you can pass the address of a pointer, change what that points to in a function, and then the variable outside the function has indeed changed to point to a new chunk of memory. Java only has primitives and pointers to objects, and it only allows you to pass those by value to functions. You can't take the address of a primitive or object and pass that.
So basically in C you can pass an object (struct) or even primitive by reference... or at least you can fake it with trivial syntax. In Java you just cannot do that, and I think Java's use of the term "reference" to mean "pointer" makes some people (understandably) confused.
Not correct.
In Java, if you have an object you take the address and pass it. If you have a primitive, you pass a copy of the value. Both things are called "pass-by-value" (something that confuses a lot of people).
typedef struct _foo* Foo; public void f(Foo bar) { ... }
Which is the equivalent C++ function? void f(Foo bar) { ... }
void f(Foo& bar) { ... }
void f(Foo* bar) { ... }
It's the last one. Java passes everything by value, but non-primitive objects in Java are actually pointers (which Java inaccurately calls references), and the pointer is passed by value.Instead of comparing Java to any other language, would it not be simpler to just say what Java does?
You don't dereference a variable in Java to access it, so that would make me think reference, not pointer.
static void f(Foo x) {
x = ...;
}
// somewhere
Foo y = ...;
f(y);
The pointer value of y cannot be changed from inside f. Therefore Java is pass-by-value.Java also has restricted semantics on pointers, but that has nothing to do with the calling convention.
(Edit: Note that the object which y/x points to can be changed, but that's not the question.)
void f(const Foo& x){
...
}
My point is the semantics don't map 1:1. If you're going to say Java's references are pointers with different semantics how is that semantically different from saying Java's references are references with slightly different semantics?These are two distinct ecosystems. They use the same terminology with different meaning. That perhaps is confusing, but definitely doesn't make one or the other incorrect.
Swap is a nice litmus test.
To people who claim that Java doesn't have pointers, I counter-argument by the fact that you can make a circular doubly-linked list in Java. Thus, a reference is a pointer though with lesser capabilities than in C++. In contrast, you cannot make a circular doubly-linked list with C++ references which are object aliases.
Actually, I have the following analogy: pointer ~ symbolic link; reference ~ hard link.
Java's references are misnamed.
That's silly. Why should every other language adhere exactly to C++'s definition of a reference? 'Reference' as a concept exists outside of computer programming and Java isn't wrong to repurpose the term in a different way than C++.
Consider also that C++ has 'dependent types', despite pretty much no relationship to the more well-known definition of dependent types. There are only so many ways to name something.
It would be silly if NullPointerException were named something else.
#include <iostream>
struct node {
node(node& previous, node& next, int value)
: previous(previous), next(next), value(value) {}
node& previous;
node& next;
int value;
};
int main(int argc, char** argv) {
char buffer[2 * sizeof(node)];
node* a = reinterpret_cast<node*>(buffer);
node* b = a + 1;
node nil(nil, nil, 0);
new(a) node(nil, nil, 0);
new(b) node(nil, nil, 0);
new(a) node(*b, *b, 1);
new(b) node(*a, *a, 2);
std::cout << a->next.next.next.value << '\n';
}
§3.8¶4 says:“A program may end the lifetime of any object by reusing the storage which the object occupies or by explicitly calling the destructor for an object of a class type with a non-trivial destructor.”
We don’t need to call the destructor because we have a POD type and we don’t depend on the side effects of the destructor—there aren’t any—so we can simply reinitialise the objects. However, we have to bootstrap these with valid objects in the first place, because we have to be able to dereference “b” and “a” in order to construct the references.
node a(nil, nil, 0);
node b(a, a, 2);
new(&a) node(b, b, 1);
One thing I am not 100% sure about is whether the standard guarantees that those references to the old 'a' are valid references to the new 'a'.Also, the above works in the general case where there is a nontrivial destructor or when the runtime checks the validity of those references or traverses them at destruction time (might happen when running under a tool looking for memory leaks, for instance, or when using a reference-counting garbage collector under the hood)
In particular, node does not have a trivial copy-assignment operator. Further below it seems that classes/structs containing references do not have a standard layout. Hence, it is not a POD.
Also, the standard does not guarantee anything about your usage of reinterpret_cast.
Maybe the code you provided works on your particular implementation, but I'm willing to bet that it violates the standard in several ways.
EDIT: cool trick though. I forgot that a name is in scope and refers to itself just after it is declared, i.e., that you can refer to nil while constructing nil.
I've tried to add some insight why the OP hears (so many) >folks (incorrectly) state "primitives are passed by value, objects are passed by reference"
What I believe was my constructive addition to the topic, seems to deserve only downvotes. I'll make a reminder to not participate again in this kind of topics.
I saw the title on HN, and was like "uhhh, no shit, why is this here?". Then surprisingly, it all of a sudden it has 80 points and almost 50 comments debating the details. I don't think there's any actually real debate on how Java actually works, this must be a purely linguistic. Or as you say, "emotional".
SQL NULLs, on the other hand, is a real philosophical war. One which the wrong size is clearly wrong and need to be crushed into ashes underneath our boots. We are not debating jargon, we are defining databases which could certainly outlive our sons and daughters!!!! .. Ok, sorry. But I just don't think it's good comparison with students who just don't really get Java. Database design is largely a matter of opinion, Java method calls are not.
I honestly feel that these posts titles are just trying to pull my leg. "Java passes everything by value!" "Really? And which value is being passed?" "The reference, of course!".
Reading the content of the articles, doing some research, and actually understanding what is happening in the language are all good steps to consider taking.
In Python, worrying about whether it's "pass-by-X" paradigm is practically worthless; instead, what you want to know in Python is which types are mutable.
The confused terminology originates before you get to function calls -- you can't ask "are objects passed by value?" without first considering objects as values. Objects can't be stored in variables and objects cannot be the result of an expression. x = y does not copy an object y into an object x because objects are not values -- x and y are variables and they can only hold values, which objects are not.
From: James Gosling
Date: 1/13/11
Don Hopkins wrote:
>Hey I know it's 2011 and we're living in the future and all that, but
>there still seems to be some confusion and debate about a matter I
>thought was perfectly clear: Is Java pass by value or pass by
>reference?
Depends on your terminology. But it's kinda both. It's pass-by-value for
everything, with the twist that for class instances, the thing that's
passed-by-value is the pointer to the object, so it behaves like
pass-by-reference.
From: Don Hopkins
Date: 1/13/11
Reminds me of the controversy about Niklaus Wirth's name:
"Whereas Europeans generally pronounce his name the right way
('Nick-louse Veert'), Americans invariably mangle it into 'Nickel's
Worth.' This is to say that Europeans call him by name, but Americans
call him by value." - Introduction by Adriaan van Wijngaarden at the
IFIP Congress (1965).
It seems to be a consequence of pretending pointers don't exist -- you
also have to pretend you have variables with object values and
references, but you still can't write a swap(a, b) function. If you
think of Java object values as pointers, then it's obviously passing
references by value. But if you don't believe in pointers and think of
variables as containing objects, then it's obviously passing objects
by reference, but your view of the world is an illusion, because it's
really implemented with pointers.
Or is it??? Someone suggested a Magic Elves theory, which helps a lot
of other stuff to make more sense.
Here's the discussion from 2011 about this issue that prompted me to ask James Gosling for a clarification. You can see that many people were VERY confused, and extremely fanatical about maintaining and spreading their confusion, in spite of the fact that it directly contradicted the Java spec and the inventor of Java himself.Java is PASS BY VALUE.
http://www.theserverside.com/discussions/thread.tss?thread_i...
>But it's kinda both. It's pass-by-value for everything, with the twist that for class instances, the thing that's passed-by-value is the pointer to the object, so it behaves like pass-by-reference.
So he's saying: We call them all "chickens", but some of them walk like a duck and quack like a duck, so they're basically ducks.
You can't extract from that quote "THEY ARE CHICKENS" (all in caps)
When he says "kinda both" and "it behaves like pass-by-reference" I read some "subtle" hints saying that he thinks that basically class instances are passed-by-reference.
Continuing to say "they act like references" is wrong and how this mess keeps perpetuating.
I think he goes on to use weasel words like "kinda both" and "the twist" to mean that it's true in a more abstract sense, if you don't use the precise definition of "call by value", and you're fuzzy about exactly what you're referring to (conflating the object with a reference to the object), and vague about how many times you de-reference the pointer that you're passing as a value parameter.
That's an unfortunate shortcut that many Java books and teachers take to teach Java to people who have no prior experience with any other programming language, to avoid teaching about pointers and other implementation details.
That leads to a superficial understanding of the language, and a blind spot in their misunderstandings, which you can see on display in Mark Stock's, Mark Hedley's and Kevin Ryan's stubborn postings to this thread: http://www.theserverside.com/discussions/thread.tss?thread_i...
Java passes pointers to objects by value, which can be used to emulate some but not all aspects of passing objects by reference (i.e. swap).
What your argument comes down to is that you prefer to think of the reference to the object you're passing by value as being the same thing as the object itself, which is not the case. The high level behavioral effect of passing a pointer to an object by value is that you are passing the object itself by reference. But it's impossible for a Java variable to actually contain an object itself, only a reference to an object, and there's no such thing as a reference to a variable or anything other than an object in Java.
Parameter passing by reference requires being able to express a reference to a local variable of any type, including primitive types, not just an object, and you must be able to pass that reference to a function in a way that makes it possible to implement "swap(ref a, ref b)".
Unlike Java, C# does have reference parameters, and it uses the "ref" keyword to distinguish them. Since normal C# parameters are passed exactly the same way as Java parameters, and C# has a "ref" feature that Java doesn't (you can implement swap in C# but not in Java), and you argue for calling Java parameters "pass by reference", then your argument applies to normal C# parameters too, so what do you call C# "ref" parameters if not references? Or do you carry your argument to its logical conclusion, and call both C# normal and "ref" parameters "references"?
Conflating passing a reference to an object by value with passing an object or any other value by reference does not magically give you the power to implement swap, so it's not passing parameter variables by reference, it's only passing the objects that the objects that parameter variables point to by reference.
The map is not the territory.
- Pass by value, values hold object references. (java, c# objects)
- Pass by value, values hold objects. (c# structs)
- Pass by reference, values hold object references. (c# inout parameter, passing object)
- Pass by reference, values hold objects. (c# inout parameter, passing struct)
In general, the whole thing about passing a reference by value is just BS. What you need to ask is, "What am I passing to the function?"
If you are passing an object, and Java (or whatever language you are using) determines a reference (memory address or whatever), then passes that reference to the function, then you are, by definition, passing an object by reference. The important thing to focus on in this argument is, "What am I passing?" The answer for this scenario is that the programmer is trying to pass the object itself. Who cares about the address / location of the object.
If you decide to pass the reference explicitly, then you are passing a reference, not the object. This would be like explicitly passing a pointer in c++, and is apparently a controversial topic when it comes to Java. A reference will nearly always (I can't actually think of a case where it isn't) be a primitive, and therefore, be passed by value.
For argument sake, say I'm wrong about all this. My question would be, "What would it look like to pass an object by reference, and how does that differ from what is currently happening?"
The spec also says
> there must be a standard way for the compiler of the creation expression to pass a reference ... to the member class's constructor
So it seems perfectly correct to say that "objects are passed by reference", and that those references could also be referred to as values.
That last sentence is a bit backwards compared to the quote. The references are passed by value if one must put it like that. But nothing gets passed by reference in Java.
Maybe we shouldn't be shitty about that, since it doesn't really matter too much.
Just a thought.
Second novice Java programmer reads title, wants to pass objects into functions, wants to avoid expensive stack copy and writes &myObject, gets compiler error, Googles "Java pointer," and curses author of the title.
Lesson learned: author of title is either unaware of the consequences such an interpretation will cause or seeks cursing as a source of attention.
No one disagrees about what Java is doing here (that I know of).
Naming is a problem if people are writing bugs due to the poor explanation.
But I can't think of the last time I've actually seen bugs caused because anyone who thought that, for example, a swap() method would work in Java.
It's something that brand-new developers might muddle up, but usually they'll learn how it works within the first year, no? If they keep track of how to treat primitives vs. objects in methods by saying "Java passes primitives by value, Objects by reference", and that works for them, that's okay. I think a senior dev should know a bit more about what's really going on, but I'm not waste the time of a mid-level programmer because, even though this code is correct, I want to talk for 20 minutes about the reason why it's correct wasn't worded quite right.
I'm far more likely to see bugs caused by people misunderstanding Java's auto-boxing/unboxing of primitives for method calls ("how the devil is this line throwing a NullPointerException?").
In c++, the only difference between a reference and a pointer is in the dereference syntax, and that a pointer can be reassigned. In the background, the variable is a pointer in both cases. It is simply syntactic sugar.
Another thing some people are mixing up is the entire philosophy between pass-by-reference and pass-by-value. The ability to write a simple swap function does not accurately demonstrate what a language is doing. It is quite simply whether or not the compiler creates a copy of the object (not a copy of the address / pointer / reference). If, in the background, Java passes an address / pointer / reference (the word makes absolutely no difference), when the programmer is attempting to pass an object, that is the definition of pass-by-reference regardless what arbitrary word I want to name the referencing value. Yes, the pointer is a copy of the previous pointer, but that's not the explicit value that the programmer cares about.
Yet another comparison to c++: the same thing happens with pass-by-reference in c++. If a function has the prototype:
void foo(Dog& d);
and I pass a Dog object in a call similar to: Dog d("Spot");
foo(d);
then, in the background, it is going create a reference (i.e. the address), and copy it on the stack. In my foo() function, the argument is simply already dereferenced (I don't have to treat it like a pointer).TLDR...
If you pass an object to a function, and operations performed by that function affect the original object, it is pass-by-reference. Period.
To demonstrate, object references/pointers/whatever:
$foo = new Foo(); // $foo
$foo2 = $foo;
$foo2->x = 3;
// $foo->x is also 3 now, $foo and $foo2 point to the same Foo object
// that is, $foo and $foo2 both contain an object handle/pointer/reference/whatever that points to the same Foo object
PHP references: function swap(&$a, &$b) {
$temp = $a;
$a = $b;
$b = $temp;
}
$a = 3;
$b = 2;
swap($a, $b);
// $a is now 2, $b is now 3It's an unfortunate situation, and it gets worse when you add array-like-objects into the mix, which look exactly like "normal" arrays up until the moment everything explodes into WTFs.
This is analogous to a C++ swap(Type&,Type&). The main difference is that C++ provides a default assignment operator for types, meaning you don't have to provide Assign yourself. A smaller difference is that the temporary instance can be created on the stack in C++ but not in Java.
For primitive types it's absolutely true that you cannot implement swap (unless you were to have created that value type in a reference-type wrapper). It's misleading to say you can't do so for reference types.
The article (and the correct pass-by-reference litmus test) swaps the values of the variables as the caller sees them, using operations inside the swap routine.
Your example swapped the contents of the pointed-to objects, but did not change the values of the variables a1 and a2.
If you want to see the difference, assign a1 to a new variable a3 before the a1/a2 swap call. A real pass by reference swap will end up with a3 == a2, and your example ends up with a3 == a1.
May I invite you to write some code and see for yourself? Here:
C++ Swap (what you and the article call the litmus test): https://gist.github.com/anonymous/06b9251a37008d158f59
Java Swap (exactly the same thing): https://gist.github.com/anonymous/d57d272579079b4e9ee8
These programs don't only output the exact same thing, they do exactly the same thing (except the differences I noted above, about the default copy assignment operator being implicit in C++, and about C++ putting the temp variable on the stack instead of the heap).
> May I invite you to write some code and see for yourself?
Sure. I've fixed your examples so they are analogous to each other and added the check that I described in my previous post.
C++: https://gist.github.com/anonymous/9c66999844afcab15eeb Java: https://gist.github.com/anonymous/bac324b3f3c13f263e14
[1] https://stackoverflow.com/questions/934775/changing-value-af...
Dog d;
is exactly like C++'s Dog *d;
Following a pointer and calling a method d.setName("Fifi");
is exactly like C++'s d->setName("Fifi");SomeType temp = arg1;
This would do a deep copy of the object pointed to by the ref arg1. What is intended is probably
SomeType& temp = arg1;
You can't do a generic swap without 3 deep copies.
If you change temp to be a reference, then once you do "arg1 = arg2", you just lost any way to get arg1's value back.
Dog dog[] = { new Dog };
void method( Dog dog[] ) { dog[0] = new Dog(); }
Having this of side effect as a default would be an insane idea ofc., so I am not sure what you are complaining about :-)
They target many people who host highly linked articles this way. They picked Serbo-Croatian because you're unlikely to verify it.
Do not post translations unless you trust the translator (perhaps because you paid them to do good work) or know the language.
It's a well know fact that Java has pointers given that you have NullPointerException as an exception.
While Java technically has pointers (in the sense that it has pointer types), it has dulled them so that you can't hurt yourself with them the same way that C (and C++) permit.
void <T> swap(T a, T b) {
// use the Unsafe to copy a's memory to a temp buffer
// then copy b's memory to a
// then copy a's memory to b
// Caution: Don't pass Integers or anything, okay
}
Or, if the objects are Beans, just iterate the properties and swap them one by one. In fact, if you know you're dealing with beans, the two don't even have to be the same class, as long as their properties and types are the same. X a = new X("foo");
X b = new X("bar");
X c = a;
swap(a, b);
// after this, a points to X("bar") and b points to
// X("foo"), but c should remain pointing to X("foo").
If you swap the contents of the object, c would point to X("bar").In C you can pass a pointer, and a pointer to a pointer. I understand both cases are usually called "pass-by-reference". If you call "pass-by-value" to passing a pointer, then the notion of "pass-by-value" and "pass-by-reference" are not very useful.
IMHO "pass-by-reference" means you can mutate the attributes of the thing passed (as in java when you pass an object) and also means you can be operating on a "volatile" area of memory, meaning another thread can CHANGE the data while the function is executing.
OTOH "pass-by-value" means you get a "snapshot" of the value at the point of the function-call, the copy is normally on the stack, and no other thread will change the data while the function is running. Also you can mutate the area with gusto without worrying of data-races, side-effects or altering the calling function variables.
This two "definitions" of pass-by-value and pass-by-reference are the ones I find useful regarding concurrency and side-effects.
If you tell me that passing an integer and passing an object are both the same thing (pass-by-value) in Java, then I will tell you that pass-by-value and pass-by-reference are not very useful concepts.
Sorry, but having an 'opinion' about such definitions doesn't help. Just [use the definition](http://en.wikipedia.org/wiki/Evaluation_strategy#cite_note-1). This clearly states what the article tried to explain with helpful examples.
> If you tell me that passing an integer and passing an object are both the same thing (pass-by-value) in Java, then I will tell you that pass-by-value and pass-by-reference are not very useful concepts.
They are useful, just not in the way that you think of them. You could use these definitions to have a meaning in terms of side-effects, but only if you design your objects accordingly, i.e. there are no exposed methods to do an in-place change of your object's data, instead you only have class functions that return a new object and read-only accessor methods. Combining this with a language that is strictly pass-by-value (such as Java and a subset of C++ without reference parameters) should make your program side-effect free.
I don't think that's a very strong argument.
For one, it's not really useful to be totally prescriptivist, especially when talking about just-birthed fields like computing.
Also, consider the usage on that page of "data structure" where it's implied that you can't have a stack-allocated data structure (namely that data structures aren't value types, even those containing pointers). Such a distinction seems remarkably unusual to me, indicating that it's best not to take that page as gospel.
Personally I prefer to avoid these terms altogether because on the rare case that it would be useful to use the words, it's rarely worth the inevitable argument.
[1] such as Kay, Ritchie, Dijkstra, Engelbart or even Matsumoto, Van Rossum, Eich, Crockford.
swap(a, b);
You have to write swap(&a, &b);