Real programming languages
From Spivey's Corner
This page uses concepts from the course to shed light on the way names, values and scopes work in some real programming languages. It shows, if anything, that the vocabulary we develop in the course can be used to give a more precise account of these things than is given in various informal accounts.
Contents |
Java
"In Java, primitive types are passed by value, and object types are passed by reference."
It doesn't actually say that in the defining documents of Java, but it's a common misconception. In truth, all parameters in Java are passed by value, but we need to be clear what values exist in Java.
For primitive types like int and char, the values are clear. For object types, the values are (what I've elsewhere called) object identities.
Suppose that the class A has a (public) instance variable int x, and we declare a and b as
A a, b;
Then we can use a.x as an expression that (provided a is not null) yields the value that is currently stored in the x slot of the object whose identity is stored in a. And we can also write a.x = 3 in order to set that value in that slot. Thus a.x is an expression that denotes a location and evaluates (as is common) to the value contained in that location. An object consists (among other things) of a collection of such locations, one for each instance variable; it has some other stuff to do with the fact that it belongs to a class that may have methods, but let's leave that aside (for now). This is similar to our analysis that explained an array as a collection of locations, with the possibility of using arithmetic on addresses to implement indexing.
We can also write the assignment a = b to copy the identity stored in b and store it also in a. This implies that these object identities are expressible (and storable) values in Java, and in fact the value of any variable of object type is one of these identities, and not an object, despite the language used in Java books.
The meaning of parameters in Java follows very simply from the statements that parameters are passed by value and that object identities are values. Since knowing the identity of an object allows us to change it by assigning to its public instance variables or calling its public methods, it is certainly true that if a function receives (the identity of) an object as an argument, then changes made to an object from inside the function also affect the object as seen from outside the function. But that's a different thing from having assignments to the parameter inside the function affect the value of the actual parameter.
JavaScript
Pascal-like languages
The ML family
| Programming Languages |
| Syllabus |
| Outline |
| Problems |
| Labs |
| Software |
| FAQ |