14 ms·
This article is overly pedantic. Java's semantics are pass-by-value only of you consider that the "values" that are being passed are pointers. But Java doesn'
by lisper 9y ago
This article is overly pedantic. Java's semantics are pass-by-value only of you consider that the "values" that are being passed are pointers. But Java doesn't have first-class pointers, it has implicit pointers. The only thing you can do with a Java pointer "value" is to tacitly dereference it.
In fact, you can write a swap(x,y) function in Java. It goes something like this:
class foo { int value }
void swap(foo x, foo y} {
int temp = x.value;
x.value = y.value;
y.value = temp;
}
(Yes, I know this isn't valid Java. Cut me a little slack here, OK?)
"But that's cheating" you protest. "That's not swapping the value of X and Y, that's swapping the value of a slot in the values of X and Y, which happen to be objects." Well, yeah. So? Compare that to this C code:
struct foo { int value }
void swap(struct foo x, struct foo y) {
[same code as above]
}
The effect of this function will be DIFFERENT. Specifically, the C function will have no effect while the Java function will swap the value slots of X and Y because C lets you pass a structure as a value while Java does not. All Java "values" are (tacit) pointers to objects [1]. Pounding your fist on the table and insisting that Java is pass-by-value because you can't write a swap(x,y) function obscures this crucial difference.
[1] OK, it also has ints and floats of various sizes. But that's really it.
- colanderman 9y agoBut Java isn't pass-by-reference. Saying so is simply wrong, for exactly the reasons you write off as "pedantry". I see this play out all the time with co-workers who are new to Python (which has the same semantics) being very confused about why "numbers are passed by value but objects are passed by reference". Pedantry matters in our profession. Details have consequences.
- lisper 9y ago> But Java isn't pass-by-reference I didn't say it was. I said that insisting it is pass-by-value isn't helpful. The real problem here is that we have only two terms which we're using to try to distinguish between three different concepts.
- tonysdg 9y agoPersonally, I'd argue there's only one concept -- pass-by-value -- with a whole lot of language-specific syntactic sugar as to what is getting passed by value. But I'll call myself out on that being even more pedantic than the current discussion.
- seanmcdirmid 9y agoThat sounds like Robert Harper’s argument that all languages are statically typed, it’s just that some languages only have one type.
- twic 9y agoI've heard this term "unityped", but i'd always written it off as a politically correct way of saying "untyped". Is there actually a worthwhile argument for it? Having thought about it for a minute or two, it seems pretty silly to me . Types are all about restricting the set of values an expression can have, and restricting the set of operations you can perform on an expression, such that any operation you're allowed to perform on a value will always do something sensible. Untyped languages don't do that, which makes them quite different from typed languages. But then i've only thought about it for a minute or two. I could imagine a genuinely unityped language. Perhaps one where every value is a vector of real numbers with an infinite number of zeroes on the end, and the operations are piecewise arithmetic, dot products, interleaving, appending, etc. That would behave quite differently to the languages where you get "undefined is not a function" and friends.
- qznc 9y agoUntyped languages actually allow you to perform any operation on any value and will always do something sensible. The sensible thing to do is to throw an exception in most cases.
- seanmcdirmid 9y agoThe difference between safe dynamically typed and untyped is whether the throw will happen or not. There are degrees of safety even in dynamically typed languages.
- tonysdg 9y agoI'll second this. As someone who spends most of their time flipping between C and Python, the details of how parameters get passed between functions is intimately related to each language, and keeping it all clear meant having to understand the nuances. Plus, I'd argue it's a lot easier to teach the nuances from the beginning rather than have to break someone's assumptions 4 years down the line (e.g. the traditional time of an undergrad CS education).
- lmm 9y ago> But Java isn't pass-by-reference. Yes it is. The thing that we talk about when we talk about "the value of foo", in Java, is passed by reference.
- lisper 9y ago> > But Java isn't pass-by-reference. > Yes it is. And this is my point in a nutshell. This argument will never be resolved, and so continuing to argue over it isn't helpful no matter how hard you pound your fist on the table.
- colanderman 9y agoThe argument is resolved pretty simply by considering that the term "pass-by-reference" was defined well before Java even existed, and that Java does not exhibit behavior required of that calling style. (In Java, you cannot change a variable in the caller's scope to point to a different object.) Java is demonstrably not pass-by-reference. But don't take my word for it. Pass-by-reference was understood by the person who invented the calling style used in Java (Barbara Liskov) not to apply to that calling style. [1] The argument was resolved before it could even be had, 44 years ago. [1] https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sh...
- esrauch 9y agoJava is also demonstratably not pass-by-value (for objects). It is a false dichotomy to prove it is one by proving it is not the other.
- mbrock 9y agoYou might think that the value of foo is that which is compared when evaluating foo == bar, which is a pointer!
- lmm 9y ago> You might think that the value of foo is that which is compared when evaluating foo == bar Few if any working Java programmers do think like that though. Like, if you have String x and String y, and println(x); prints "foo" and println(y) prints "foo" and x != y (a perfectly ordinary situation to get into in Java), we would still say "the value of x is "foo"".
- coldtea 9y ago>Pedantry matters in our profession. Details have consequences. Well, if so, even more reason NOT to say "Java is Pass-by-Value". Instead, you should be a good pedant, and explain the Java passing model, its caveats and edge cases, in its entirety. If details matter, don't throw some BS blanket statement like "Java is Pass-by-Value" around, that can be misinterpreted in 200 ways, and that doesn't capture the whole nuances of what's going on.
- colanderman 9y agoAs I said elsewhere in this thread, personally I use the term "pass-by-pointer-value". Barbara Liskov used the term "pass-by-sharing" (actually "call-by-sharing") when she invented the damn thing in 1974. [1] "Pass-by-reference" is simply wrong, as it implies behavior which Java does not exhibit. [1] https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sh...
- coldtea 9y ago>As I said elsewhere in this thread, personally I use the term "pass-by-pointer-value" Well, that doesn't apply exactly to ints and longs though...
- haglin 9y agoYou need a controversial title, or the topic will be ignored and not discussed here.
- zephyrfalcon 9y agoOK, but in Python this isn't actually true... numbers are not passed any differently than other kinds of objects. As such, it does not have the same semantics as Java, which does distinguish between primitives and non-primitives. Of course, this kind of discussion isn't new to the Python community either. The actual calling convention is somewhere between call by value and call by reference, sometimes called "call by object". This is well worth reading: http://effbot.org/zone/call-by-object.htm http://effbot.org/zone/call-by-object.htm
- colanderman 9y agoNo, Java makes no such distinction in passing. Java does have values which are not object pointers, but, just like object pointers, they are passed by value, and behave exactly the same as an immutable object in either language.
- masklinn 9y ago> This article is overly pedantic. Java's semantics are pass-by-value only of you consider that the "values" that are being passed are pointers. Which is exactly what they are. > But Java doesn't have first-class pointers, it has implicit pointers. The only thing you can do with a Java pointer "value" is to tacitly dereference it. So? Just because you're not given direct access to the value itself doesn't change the semantics of the language. If you assume "pass-by" is strictly dichotomous and the choices are either value or reference, then Java can only be pass-by-value, its semantics simply don't allow the possibility of it being pass-by-ref. IIRC the Python community calls it "pass reference by value", sadly they seem to be more or less the only ones doing so. CLU called it "pass by sharing". > All Java "values" are (tacit) pointers to objects [1]. Pounding your fist on the table and insisting that Java is pass-by-value because you can't write a swap(x,y) function obscures this crucial difference. Then again that Java's boxed types are boxed seems pretty obvious...
- lisper 9y ago> If you assume "pass-by" is strictly dichotomous and the choices are either value or reference Well, there's your problem right there: pass-by is not "strictly dichotomous." There are (at least) three different argument-passing disciplines in common use. If you insist on using only two words to distinguish among them you will cause unnecessary confusion.
- masklinn 9y ago> Well, there's your problem right there It's not my problem, it's yours. > pass-by is not "strictly dichotomous." Which you may have wanted to explain in your essay if you believe it instead of going on worthless rants. > If you insist on using only two words to distinguish among them you will cause unnecessary confusion. I don't.
- evrydayhustling 9y agoDisagree - the distinctions you are talking about (no pointer arithmetic) has much less to do with "pass by value" than the OPs points. Also, at the risk of being what you are calling pedantic, dereferencing is not the only thing you can do with an object pointer in Java. You can also check nullity, equality, and cast the object. These are substantive actions with semantics that are outside any particular object's implementation. Really, the only thing i can think of that you can't do with Java pointers that you can with other languages is pointer arithmetic - and that's due to Java's original reason for being: making portable code where object implementations could be isolated from memory allocation inner workings.
- lisper 9y ago> You can also check nullity, equality, and cast the object Fair enough (though checking nullity is just a special case of checking for equality). > the only thing i can think of that you can't do with Java pointers that you can with other languages is pointer arithmetic Well, yeah, but it's not like pointer arithmetic is some obscure little feature that is hardly ever used. Pointer arithmetic is the thing that distinguishes C-like languages from Lisp-like languages. If you're trying to explain a distinction among programming languages that involves pointers you can't just sweep pointer arithmetic under the rug as if it were a trivial detail.
- masklinn 9y ago> Well, yeah, but it's not like pointer arithmetic is some obscure little feature that is hardly ever used. Pointer arithmetic is the thing that distinguishes C-like languages from Lisp-like languages. That's not really convincing given many languages have pointers (as a directly manipulable concept) and actual pass-by-value but no pointer arithmetic unless you call into some sort of unsafe escape hatch. > If you're trying to explain a distinction among programming languages that involves pointers you can't just sweep pointer arithmetic under the rug as if it were a trivial detail. Sure you can.
- danbruc 9y ago
- stonemetal 9y ago>The effect of this function will be DIFFERENT. Obviously the output will be different the input was different. The equivalent C code would have passed pointers. In that case the behavior would have been identical passed in values not swapped contents swapped. Just because Java only has object references, doesn't mean they aren't references.
- matchagaucho 9y agoThese pedantic discussions are dangerous. The purpose of teaching new programmers value vs reference is to make them aware of the dangers of mutating objects passed to functions. public static void main(String[] args) { MyClass c = new MyClass(); c.Message = "Hello"; c.ID = 1; mutate(c); System.out.println(c.Message); // "Goodbye" System.out.println(c.ID); // 2 } public void mutate(MyClass c){ c.Message = "Goodbye"; c.ID = 2; } public class MyClass{ public String Message; public Integer ID; }
- Asooka 9y agoC also has only pass-by-value semantics. The difference is that you can take the address of a variable, i.e. you can stack as many layers of references as you want. In case of the C++ swap: template<class T> void swap(T& a, T& b) { T tmp = a; a = b; b = tmp; } When called as int a=1, b=2; swap(a, b); The variables a and b are passed by reference, or you can think of it as an implicit pointer. This is the meaning of pass-by-reference - changes made to the value of a variable directly impact the referred-to variable. Pass-by-reference can be confusing and its inclusion in C++ is useful as immutable non-null pointers, a use which modern languages support in various other ways. Thinking of Java objects as pointers to objects might be a bit confusing at first as well, but it's the correct mental model for what's happening under the hood. It all goes back to understanding computation in the context of a von Neumann machine with addressable random-access memory, and knowing that values are stored in numbered memory cells, so variables can be either the memory region itself, the memory region's number, which itself can be stored in a memory region whose number can be stored in another ... etc. You can't abstract away the basic properties of the computing architecture we use, so it's a good idea for programmers to have mental models of computer memory and programming language variables that are fundamentally congruent with the von Neumann architecture.
- kazinator 9y ago> Pass-by-reference can be confusing and its inclusion in C++ is useful as immutable non-null pointers You can easily bind a C++ reference to a null pointer. Your compiler will silently accept it and the behavior will be predictably that &ref == 0 will evaluate true. E.g. // if OOM, &ref is null object &ref = *new (std::nothrow) object(args, ...); Of course, it's not defined behavior; i.e. wrong on paper. (If only a paper tiger could defend you against a real flesh-and-horn charging rhinoceros, ...) Whether or not it's defined is moot; the fact is you can commit undefined behavior with references. They are just pointers in disguise: wolves clad in sheepskins. References inside class/struct objects are real pointers occupying a word. If such an object is out of scope and has been deleted, and you use the reference, it's exactly the same as a use-after-free of a pointer or any other value. Through the bad reference, some wrong object will be accessed or modified. The only relatively harmless references are the lexicaly scoped ones which go away at compile time, behaving as aliases: { int x = 42, &x_alias = x; }.
- fauigerzigerk 9y ago>The only thing you can do with a Java pointer "value" is to tacitly dereference it. No, that's not true at all. Crucially, you can assign a new value, and that is where the distinction you're calling pedantic makes all the difference. When assigning to a function parameter, am I assigning to the variable passed as an argument or am I assigning to a copy of that variable? It's hard to overstate the importance of that question, and that's why these two concepts have long established names: call-by-reference and call-by value.
- lisper 9y ago> you can assign a new value No, you cannot assign a new value to a pointer. You can assign a new value to a variable whose value is a pointer, and you can assign a new value to the storage location that a pointer points to (in C, though not in Java) but you cannot assign a new value to a pointer. A pointer is just a number.
- fauigerzigerk 9y agoYou're ignoring my point, which is that you need the distinction between call-by-value and call-by-reference to explain what happens if you assign to a parameter. I think it's obvious that I was talking about assigning to pointer variables because parameters are always variables and never just values.
- lisper 9y agoI'm not ignoring your point. I'm saying that your point is not a point worth making, at least not in the context of talking about relevant distinctions among different programming languages. > you need the distinction between call-by-value and call-by-reference to explain what happens if you assign to a parameter You only need this distinction if: 1) Different programming languages actually handle this differently and 2) You actually assign to function parameters If either of these conditions do not hold then you don't need the distinction. And in fact: 1) All programming languages in use today are call-by-value by default. A very small subset of them offer call-by-reference as an option. And... 2) Assigning to function parameters is never a good idea. If you're assigning to a function parameter you are almost certainly doing something wrong.
- qznc 9y agoYou cannot write a generic swap in Java. You can in C++.
- syrrim 9y agoWhy not? Java support reflection, so you can - at runtime - enumerate all the properties of an object. From there, you would assign each property from a to b. The only thing stopping this is that not all properties will be public, but this seems like a pedantic hangup to me. They are functionally equivalent.
- adrianmonk 9y agoSubclasses and final fields make this impossible in the general case.
- ChuckMcM 9y agoI believe the author was being as pedantic as they were in order to avoid having the discussion you just brought up. Java doesn't do "object assignment" so you cannot say Foo d = new Foo(...); Foo c = d; And get two objects, you have two references to the same object. If you invoke a method on c or d it will be dispatched to the same code. So c.SetVaueX(10) and print d.GetValue(x) will show you the same value of 'x'. In C++ or other pointer languages you could have *d = *c which would do an assignment of the bits from one to the other, then manipulating d would manipulate its copy of the bits and manipulating c would manipulate its copy of the bits.
- catnaroek 9y ago> Java's semantics are pass-by-value only of you consider that the "values" that are being passed are pointers. All values in Java are indeed either primitives or pointers. You cannot define your own values! How is anyone supposed to call this a high-level language?
- SeanLuke 9y ago> This article is overly pedantic. Java's semantics are pass-by-value only of you consider that the "values" that are being passed are pointers. ??? Pretty sure Java is uniquivocably pass-by-value. Your example of Swap is simply incorrect. IIRC, in a pass-by reference language, Swap could be written as swap(int x, int y): int z = x; x = y; y = z; And then you could call it as: int a = 4; int b = 5; swap(a, b); // b now is 4 and a is 5 This can't be done in Java. Also Java's reference types seem to be pretty FCO to me. Just because Java don't have pointer arithmetic is hardly a disqualification. BTW, I find it interesting that Java's argument passing semantics and Common Lisp's are, so far as I can tell, identical.
- dfox 9y agoThe semantics are mostly identical in most OO languages with C++ being one notable exception.
- pjmlp 9y agoThat notable exception exists at least in Object Pascal, Oberon, Oberon-2, Active Oberon, Component Pascal, Modula-2, Modula-3, Ada, Eiffel, Sather, D, Swift.
- dfox 9y agoI probably should have qualified that with "widely used". :) On the other hand this list is to some extent relevant to the point I was trying to make, as most of these languages are somehow related to Algol/Simula/Modula (as is C++) and not to Lisp/Smalltalk (as is Java, Python, .net...). Object Pascal has the problem that there are at least two unrelated languages with same name. And the duffernce between Borland Pascal 7 and the Object Pascal used by Delphi is that the latter is firmly in the camp "there are only references to objects". (ie. for classes defined by 'object' keyword common pattern was "PFoo = ^TFoo", while for the 'class' ones, eg. essentially whole VCL, this is implicit)
- pjmlp 9y ago
- kazinator 9y agoYour propositions is wrong here in the following way. Suppose we have local variables A0, B0 and A1, B1. A0 and B0 hold references to objects O and P, respectively. A1 and B1 also hold references to this same pair of objects, respectively. Because Java is pass-by-value, you cannot write a function which appears swaps A0 and B0 without also appearing to swap A1 and B1 which are not passed to it. If we swap A0.content with B0.content, then there will be the unintended consequence that A1 and B1 also swap. Swapping the referenced content isn't the same as swapping the variables; we can tell the difference because the change is not confined to just the specified variables. Now you could argue that A0 and A1 aren't really different variables. But, undeniably, they are; even if they initially refer to the same object, they can be mutated not to. Or, if the variables are not mutated, perhaps they are initialized to the same object in some instantiations of the lexical scope and to different objects in other instantiations of the scope.
- marvy 9y agowell put
- pdpi 9y ago> Pounding your fist on the table and insisting that Java is pass-by-value because you can't write a swap(x,y) function obscures this crucial difference. Swap is just a convenient example. Ultimately, if rebinding the function argument has no externally visible effect, it's not pass-by-reference, but rather pass-pointer-by-value — In C++ terms, a Java method with signature `foo(T arg)` is akin to C++'s `foo (T * const arg)` rather than `foo(T &arg)`.
- cryptonector 9y agoTFA is overly pedantic, but your swap() method is not generic and falls apart if the class has more than one instance variable. In Lisp, for example, it's trivial to write a swap macro -- not very fair, I suppose. In Tcl you can have a proper swap that is not a macro (which is good, since Tcl does not have macros!) by using Tcl's pass-by-name semantics. In C++ you can just declare the arguments as references and then you won't notice at the call site that the arguments are being passed by reference -- super convenient, but then somewhat scary as well. And so on.
- itronitron 9y agoyour comment might make sense if you wrote it up as valid Java, as it is I think you are losing a lot in the translation
- adrianmonk 9y agoYour swap() method violates the liskov substitution principle. If Java had pass-by-reference, you could write one that doesn't.