2.) Call by value the way Java does it is faster for the computer than call
by reference. Call by vaule requires one less level of indirectness in
addressing.
3.) With call by reference, the callee CAN modifiy the caller's variables,
but that is no guarantee that it actually does. Java's scheme is crystal
clear which variables are input and which output.
4.) My academic background is mathematics. Mathematicians have some set
ideas about what functions should do. z = f(x,y) is a black box that looks
up x and y in some mapping and produces z. Output is on the left. Input
on the right --- just the way call by value works. Fortran stole the
notation from mathematics. Computer science should use it correctly.
-------------
If someone were dead set on adding the underlying capababilites of call by
reference to Java I would prefer it be done a novel syntax, so that the
clear distinction between input and output variables is maintained at the
place where the method is called.
currently we have:
output = funcName(inputs);
Perhaps you could do something like:
output = funcName(inputs)(in/Outputs)(additionalOutputs);
or
output = funcName(inputs) inout(in/Outputs) out(additionalOutputs);
Another way the confusion could be softened if call by reference were ever
added to Java would be to have the source code browser flag call-by-ref in
a special colour different from the ordinary one used for call-by-value
variables and expressions in the place where methods are called, not just
in the argument definition.
Ro...@bix.com <Roedy Green of Canadian Mind Products> contract programming
-30-
|| currently we have:
|| output = funcName(inputs);
|| Perhaps you could do something like:
|| output = funcName(inputs)(in/Outputs)(additionalOutputs);
|| or
|| output = funcName(inputs) inout(in/Outputs) out(additionalOutputs);
You know what I want see? Tuples. How many times have you ever
wanted to return two or more things, but couldn't because C/C++/Java
only lets you return one thing. It is a complete pain to create
a structure or class to hold two return values. Tuples let you
return more than one thing. Hence you could have something like
( output1, output2, output3 ) = funcName( inputs );
then use the various outputs as needed. That's what I'd like
to see.
--
Charles Lin
cl...@cs.umd.edu
Why not use something like Python's tuples:
class SomeClass {
public (int, int, int) someMethod(int, int, int);
}
(a, b, c) = obj.someMethod(a, b, c);
Simple, clear, mathematically-correct, and avoids all the disadvantages you
list above.
David Hopwood
david....@lmh.ox.ac.uk
> 1.) If you have BOTH call by reference and call by value supported in a
> language you have to look at the function definition before you can
> understand the probable effect of a function call on the parameters.
> Further you again have to look ELSEWHERE in the code to check if myParm =
> someNewValue; is going to have any effect on the caller's variables.
> Programs are typically coded by humans. Humans are lazy. They probably
> won't check. They will just ASSUME, and will of course get nailed.
This problem is entirely mitigated by good Software Engineering and good
technical documentation. IT isn't hard to keep track of especially
concidering the types of parameters that are generally passed by refrence,
InputStream, OutputStream, or for C++ istream and ostream.
> 2.) Call by value the way Java does it is faster for the computer than call
> by reference. Call by vaule requires one less level of indirectness in
> addressing.
Obviously you haven't been programing in java very long or have been passing
only primatives as parameters. Whenever anyhting derived from Object is
passed as a aprameter, it is passed by refrence, anwalys and (currently)
without exception. Objects can be passed by value if you send
myObject.clone(), but only if (myObject instanceof Clonaeble) == true. There
is a keyword reserved to allow passing "byvalue."
> 4.) My academic background is mathematics. Mathematicians have some set
> ideas about what functions should do. z = f(x,y) is a black box that looks
> up x and y in some mapping and produces z. Output is on the left. Input
Doing such would limit the versitility of some functions. Functions can
return one and only one data type, so passing by refrence allows for that
change. Also concider that many objects rely on their uses being internally
noted, such as InputStream and OutputStream noting information to their
FileDescriptors. In C++ this is even more critical for their streams seing as
they both get passed in as a variable ans passed out as a return value, pasing
by value would create multiple copies of the cout object.
> on the right --- just the way call by value works. Fortran stole the
> notation from mathematics. Computer science should use it correctly.
Computer Science is not Mathematics, or they would have left it in 90% of the
university amth departments. Mathmatical notaion can rely on the fact that
perhaps only Ph.D.s will be looking at a particular expression, Programming
notations (a central part of CS) must adjust to the fact that a finite set of
electrical switches will be interpreting the notation at many levels.
> myObject.clone(), but only if (myObject instanceof Clonaeble) == true.
And it doesn't throw a CloneNotSuppeorted exception.
> There is a keyword reserved to allow passing "byvalue."
If you mean "var" it is gone. As are most of the "reserved" reserved words.
All that is left is :
const
goto
transient
(According to "The Java Programming Language" by Arnold & Gosling).
---
Everybody - Let's get clear on what we want "call by value/reference"
to mean.
Again according to JPL (Java Programming Language) -
"All parameters to methods in Java are 'call by value'. That is the
values of parameter variables in a method are copies of the values
the invoker specified." ... "When a parameter is an object reference,
however, the object reference is what is passed 'by value', not the
object itself."
So Objects are passed by reference - not by value. Primitive types
are passed by value.
This is important, especialy for those coming from C/C++:
// mind my incorrect C code...
typedef struct X { /* a bunch of fields */ };
void f1(X x) { }
void f2(X *x) { }
When I pass an X to f1 it will be expensive.
When I pass a pointer (reference) to an X to f2 it is cheap.
If I'm being impersise feel free to correct me...
..darcy
--
D'Arcy Smith
Symantec
> Someone, how do you write a SWAP method in Java?
> You know, you've got two int variables and you want to swap the
> values. I want to know how to do this easily looking like:
>
> int a= 7;
>
> int b= 16;
>
> swap(a, b);
int ab[] = new int[2];
ab[0] = 7;
ab[0] = 16;
swap(ab);
void swap(int ab[])
{
int i = ab[0];
ab[0] = ab[1];
ab[1] = i;
}
=:-0
>Obviously you haven't been programming in java very long or have been
>passing only primitives as parameters. Whenever anything derived from
>Object is passed as a parameter, it is passed by reference, always and
>(currently) without exception. Objects can be passed by value if you send
> myObject.clone(), but only if (myObject instanceof Cloneable) == true.
>There is a keyword reserved to allow passing "byvalue."
The references themselves are passed by value, which gives the callee the
ability to meddle with the caller's objects but not to make the caller's
variables point to different objects.
It becomes a religious war as to whether to consider that call by reference
or call by value. People call each other idiots all the time when the
problem is not a misunderstanding of the mechanism but a disagreement on
terminology.
This issue has come up several times before over the past weeks and no
consensus was reached on consistent terminolgy. My own preference is to
say "Loosely speaking, primitives and references are passed by value, but
the objects pointed to by the parameters are effectively passed by value."
For practical purposes you want to know, if I change something in a method,
what happens in its caller?
The advantage of Java's rules come primarily from CONSISTENCY. You don't
have to study the far-away method header to figure out what is supposed to
happen the way you do in many other languages.
It might be nice to have some mechanism for ensuring a method does not
modify its caller's objects, but we don't have that in Java.
One thing I do know is that mixing up call by reference, call by value,
const on the pointer, const on the object, take a local copy, take a local
copy and make that const etc etc. gets very confusing and few programmers
would bother to use it correctly.
>4.) My academic background is mathematics. Mathematicians have some set
>ideas about what functions should do. z = f(x,y) is a black box that looks
>up x and y in some mapping and produces z. Output is on the left. Input
>on the right --- just the way call by value works. Fortran stole the
>notation from mathematics. Computer science should use it correctly.
Wouldn't you rather use Miranda or Haskell?
Someone, how do you write a SWAP method in Java?
You know, you've got two int variables and you want to swap the
values. I want to know how to do this easily looking like:
int a= 7;
int b= 16;
swap(a, b);
???
Sandy
--
// Alexander Anderson Computer Systems Student //
// sa...@almide.demon.co.uk Middlesex University //
// Home Fone: +44 (0) 171-794-4543 Bounds Green //
// http://www.mdx.ac.uk/~alexander9 London U.K. //
On Sunday, May 12, 1996, Alexander Anderson wrote...
> int a= 7;
> int b= 16;
> swap(a, b);
> ???
Its worth noting (or making clear) that although the above routine could
not ever perform the swap correctly, the following version could.
Integer a = new Integer( 7 );
Integer b = new Integer( 16 );
swap(a,b);
-bob
I'm just being silly here, but here's one, that you have to call three times.
static int swap (int a, int b) { return a ^ b; }
a = swap(a,b);
b = swap(a,b);
a = swap(a,b);
or
a = swap(swap(a,b), b=swap(swap(a,b),b));
------------
Here is a more Javaesque solution:
class Pair {
int first;
int second;
Pair (int first, int Second) { this.first = first; this.second = second; }
static Pair Swap(Pair p) {
return new Pair (p.second, p.first );
}
}
To use it:
Pair q = new Pair(5,10);
q = swap(q);
One way to help remember this is, objects are always accessed "by
reference" literally "via a Reference". "Reference" is Javaspeak for
pointer variable. There is no other way of getting at an object other than
via a Reference whether you are using parameters or not.
No it couldn't. (This 'solution' to passing references to primitive values
seems to be gaining something of the status of an urban myth.)
The wrapper classes in java.lang are immutable; you cannot change the wrapped
value after creation, nor can you inherit from them. To do something
equivalent, you have to create your own wrapper classes which have a method
to set the current value.
I've written a set of these; they're called IntegerBuffer, etc. (in analogy
with String and StringBuffer). If you don't want to write your own, I'll be
releasing them at the same time as the extensions to support dynamic method
look-up.
David Hopwood
david....@lmh.ox.ac.uk
That would be slick. Mesa had that feature and I used it a lot.
However, you can pretty much do it already in Java using a class.
See for example http://www.acme.com/java/software/Acme.Pair.html
And while you're at it, http://www.acme.com/java/software/Acme.Refs.html
lets you do call-by-reference as well.
---
Jef
Jef Poskanzer j...@acme.com http://www.acme.com/jef/
"Refreshing as a summer breeze. Delightful as a dip in the sea."
The problem with this is that a swap function is really only useful on
Lvalues (okay, in parsing it can be useful for non Lvalues), and so you might
as well use a temp variable since after creating your Pair class, swapping and
reassigning the pair class, you must asign the swapped values to the Lvalues
you were originally going to assign to.
Just my (int)Math.E cents.
--
Life - F'jord of Timelord, James Lynn
Java - http://www.undergrad.math.uwaterloo.ca/~j2lynn/java.html <NEW LOCATION>
SuperButton v1.1 and MessageBox v1.0 available there
Actually, a more accurate description would be, the Objects in java are
all references that are passed by value. The reason why Objects cannot
be considered as being passed by reference is illustraited in the following
code:
public class ValueVSReference
{
void foo(String bar)
{
bar=new String("Pass by reference");
}
static void main(String args[])
{
String theJudge="Pass by value";
foo(theJudge);
System.out.println(theJudge);
}
}
And what does theJudge say?
Pass by value
Well, if you really need it all on one line, and they are not of the
float family, you could always do
a^=b^=a^=b; //swap(a,b);
but without a preprocessor, this can be unweildy (and with a preprocessor,
prone to bugs).
I say this having just created a 900K Kerberos DLL that Java hooks into.
Bleah.
Carpe diem,
Matt
On Mon, 13 May 1996, James F'jord Lynn wrote:
>
> Well, if you really need it all on one line, and they are not of the
> float family, you could always do
>
> a^=b^=a^=b; //swap(a,b);
>
> but without a preprocessor, this can be unweildy (and with a preprocessor,
> prone to bugs).
>
> --
> Life - F'jord of Timelord, James Lynn
> Java - http://www.undergrad.math.uwaterloo.ca/~j2lynn/java.html <NEW LOCATION>
> SuperButton v1.1 and MessageBox v1.0 available there
>
>
Matthew Travis, Project Lead mtr...@uiuc.edu
WebOS, Kerberos-J Project http://www.students.uiuc.edu/~mtravis
The network is the computer... but a very slow one
Java has object references as data types. This means that object
references are passed by value. All variables hold either primitive
types (long, double, etc.) or references to objects. You cannot pass
an *object* by value because you cannot have an object to pass. You
can only have an object *reference* value, and that (of course), you
can pass.
The result is that if the value you pass to a method is a *reference*
to an object, changes in that object are visible after the method
returns. So, given
class Pair { int x, y; }
class SomeClass {
void clearPair(Pair clearit) {
clearit.x = clearit.y = 0;
}
void foo() {
Pair p = new Pair();
p.x = 7;
p.y = 12;
clearPair(p);
System.out.println(p);
}
}
The fields of "p" in foo() will modified after the call to clearPair,
because the reference "p" in foo() refers to the same object as the
refernce "clearit" in clearPair.
Ken Arnold
Ah that one is easy. You can't. You can do this, though.
public class test {
static void swap(int[] r) {
int t = r[0];
r[0] = r[1];
r[1] = t;
}
public static void main(String args[]) {
int[] arr = { 7, 16 };
swap(arr);
System.out.println("a: " + arr[0] + " b: " + arr[1]);
}
}
--
Lars Balker Rasmussen <URL:http://www.daimi.aau.dk/~gnort/>
C++ is a ridiculously complicated travesty that few have the excess IQ
points to understand enough not to screw up massively. --Tom Christiansen
No, Danno was right. There were both a "byvalue" and a "var". Check
1.5 in the language spec.
> All that is left is :
>
> const
> goto
> transient
Has transient been demoted to a "reserved" reserved keyword? It is not
listed as such in the spec.
> (According to "The Java Programming Language" by Arnold & Gosling).
Awwww.
I kinda liked the future reserved keyword. Or is that reserved future
keyword?
(What was that for anyway? Being liked by weird people like me?)
>>Its worth noting (or making clear) that although the above routine could
>>not ever perform the swap correctly, the following version could.
>>
>>Integer a = new Integer( 7 );
>>Integer b = new Integer( 16 );
>>
>>swap(a,b);
>
>No it couldn't. (This 'solution' to passing references to primitive values
>seems to be gaining something of the status of an urban myth.)
>
>The wrapper classes in java.lang are immutable; you cannot change the wrapped
>value after creation, nor can you inherit from them. To do something
>equivalent, you have to create your own wrapper classes which have a method
>to set the current value.
>
>I've written a set of these; they're called IntegerBuffer, etc. (in analogy
>with String and StringBuffer). If you don't want to write your own, I'll be
>releasing them at the same time as the extensions to support dynamic method
>look-up.
Phew. I can breath again.
Are you going to place these in a "central" (?) Class Warehouse?
>> Someone, how do you write a SWAP method in Java?
>
>I'm just being silly here, but here's one, that you have to call three times.
>
> static int swap (int a, int b) { return a ^ b; }
>
> a = swap(a,b);
> b = swap(a,b);
> a = swap(a,b);
>or
> a = swap(swap(a,b), b=swap(swap(a,b),b));
Does anyone know of a good Java Quine class that writes out it's own
source code, in the style of Godel, Escher and Bach?
Yoo-hoo! van der Lin-den!
Thanks in advance,
--
It seems that terminology is the problem. We have references to objects,
and are talking about calling by reference. Perhaps what we need is a
new name for object references. The term "handle" immediately pops to mind,
but that may be used in too many other paradigms already.
Once we have a new name for object references, it should be far less
confusing for newcomers to understand that objects are passed by reference,
where the (insert new term for "object references" here) are passed by value.
-g
----------------------------------------------------------------------------
Graeme Hiebert Email: g...@mda.ca
MacDonald Dettwiler and Associates g...@uniserve.com
Richmond, B.C. CANADA Phone: +1-604-231-2313
I'll send a reference to Gamelan (www.gamelan.com), which seems to be the
nearest thing to that so far.
David Hopwood
david....@lmh.ox.ac.uk>
If you get user-defined value types, and genericity (all of which
ought to come into Java), then you almost get tuples for free, as a
user-defined class.
Sather does it.
: --
: Charles Lin
: cl...@cs.umd.edu
You could kludge that now in Java with:
object [ ] someMethod( object [ ]) {...}
object [ ] domain = { a, b, c };
object [ ] range = obj.someMethod (domain);
d = range [0]; e = range[1]; f = range[2];
Adding tuples would have many difficult syntactic repercussions. ( )
already perform extended duty to mark casts, functions and operator
precedence override. However if it could be done cleanly, it might in one
bold stroke get rid of much of Java's verbosity. e.g.
{a,b,c}.someMethod(); instead of a.someMethod(); b.someMethod();
c.someMethod();
Print({a,b,c}); instead of Print(a); Print(b); Print(c);
{a,b,c} ++; instead of a++; b++; c++;
The problem is there are already tuple-like things in Java -- array
constructor/initialisers, arrays, and parameter lists, not to mention
classes with public instance variables, (casts) and for(,,) loops. Adding
yet another variant is likely to cause confusion. If they are ever added
we will likely need to create some new flavours of ( ) [ ] { } < > to
represent them unambiguously.
What I have seen some of the technical documents say is that Objects are
passed by Handle rather than by Value or Reference. The counter to your
illustration would be:
public class ValueVSReference
{
static void foo(StringBuffer bar)
{
bar.insert(5, "not ");
bar.append(", but by handle");
}
public static void main(String args[])
{
StringBuffer theJudge= new StringBuffer("Pass by value");
foo(theJudge);
System.out.println(theJudge);
}
}
Microsoft(R) Windows 95
(C)Copyright Microsoft Corp 1981-1995.
[WINDOWS] C:\WINDOWS>java ValueVSReference
Symantec Java! ByteCode Compiler Version 1.00b
Copyright (C) 1996 Symantec Corporation
Pass not by value, but by handle
[WINDOWS] C:\WINDOWS>
The mapping of Java to C++ is to some extent imprecice, java maps much
closer to C, concider this
java in C/c++ this more closly maps to:
------------------------- -----------------------------------
Object foo; Object *foo;
foo.doSomething(); doSomething(foo);
/* or in C++ foo->doSomething() */
class foo extends bar class foo:bar
{ {
/* /*
... ...
*/ */
void doAnother(foo that) void doAnother(foo *that)
{ {
doSomething(); this->doSomething(); // or just doSomething();
that.doSomething(); that->doSoemthing();
that = new foo(); that = new foo();
}; };
}; };
Anyone who has survived introductory C programming in College remembers
the fun that was had de-cyphering pointers. Sorry if this brings back bad
memories. As best I can remember these will do exactly the same thing. If
doSomething changes values inside the Object that, then the changes will take
affect in the that that was passed in, i.e. the scope of change exceeds the
method invocation(such as a mutable string). But if you make a new object, and
assign it to the new handle, then you are no longer pointing to the Object that
was passed in, but pointing to the Object you created. The scope would then
only extend to the life of the Object created, which can by later actions exceed
method invocation.
Basically you can concider all "." refrences in java to be "->"
references in C/C++. In Java byte code the handle of the object takes only one
register space like integers and floats, so can be treated as an index, without
any arethmetic operations.
so in a nutshell, Java has pass by value only for primitaves, and pass
by handle for Objects. (Arrays are sub-classes of Object, so this is a correct
statement.) To say Objects are passed by value or reference are both only
partialy right, and hence partialy wrong.
-- Danno
Colorado School of Mines -- undergraduate CS
>I kinda liked the future reserved keyword. Or is that reserved future
>keyword?
>
>(What was that for anyway? Being liked by weird people like me?)
A future is an expression that is calculated in the background. When a
thread needs its value, it blocks if the result is not yet ready.
For example (in some made-up syntax),
x = future(nth_prime_number(10000)); // returns immediately
// some code that does not need x
// ...
System.out.println(x); // blocks if x has not finished being calculated
I don't know if this is what the language designers were thinking of, but
it's how I've heard the term used before.
David Hopwood
david....@lmh.ox.ac.uk
> D'Arcy Smith <DSm...@symantec.com> writes:
> > > There is a keyword reserved to allow passing "byvalue."
> > If you mean "var" it is gone. As are most of the "reserved" reserved words.
> No, Danno was right. There were both a "byvalue" and a "var". Check
> 1.5 in the language spec.
I'm reading the Language Spec as of (I can't find it right now) - the current
one that only has the first 5 chapters.
I'm also reading the Java Programming Language by Arnold & Gosling.
> Has transient been demoted to a "reserved" reserved keyword? It is not
> listed as such in the spec.
That's at least what the JPL says...
> You know what I want see? Tuples. How many times have you ever
>wanted to return two or more things, but couldn't because C/C++/Java
>only lets you return one thing. It is a complete pain to create
>a structure or class to hold two return values. Tuples let you
>return more than one thing. Hence you could have something like
>
> ( output1, output2, output3 ) = funcName( inputs );
Lisp/CLOS and Dylan both let you do this: return multiple items on the
stack without enclosing them in some data structure (just as you can
pass multiple items *to* a function on the stack without enclosing
them). Although this is a moderately convenient feature that I use
mainly to avoid generating unnecessary garbage, it is hardly at the
top of my list of things I'd lobby to get into Java. First class
functions, parameterized types, a better AWT, the ability to generate
HTML and pass it back to the browser, and some form of multiple inheritance
(even restricted to disjoint variable/method names) are all much
higher on my list.
- Marty
Java Resources: <http://www.apl.jhu.edu/~hall/java>
>If you get user-defined value types, and genericity (all of which
>ought to come into Java), then you almost get tuples for free, as a
>user-defined class.
>
>Sather does it.
I don't know Python or Sather. But in the languages I've used that let
you return multiple values directly on the stack (Lisp and Dylan), one
of the most common uses was to avoid generating garbage. Ie if you
wrap two return values into a data structure and then the calling
function unwraps them and throws away the data structure, you can
generate a pretty lot of garbage. I don't see how tuples as a
user-defined class solve this problem.
Here we go again. Java uses only "call by value" argument
passing. Never "call by reference". This means that if you call
foo(x) and foo is is something like
SomeClass foo(AnotherClass a) {
a = somethingElse();
...
}
then x will *not* change. It would with call by reference.
What makes this confusing is that Java uses the term "reference" for
what it passes for the values of non-primitive objects (ie
"references" here are pointers with restricted types of operations).
Whether Java uses call by reference or call by value is independent of
the kinds of values Java uses.
Point: "call by reference" and Java "references" are two different
things.
This seems more of an illustraiton of my first point (above), than a counter
illustration of my second. The point is that Objects cannot thought of as
large contiguous membory blocks, but as references to such blocks (whether
the reference is a pointer or a handle isn't that big of a deal).
The second bit of code was to show that the passing of objects cannot
be concived of as being passes by reference, since you cannot assign a new
object them. It i the value of the Object (which is a reference) which
is passed.
Now, where is that dead horse. I have a new basball bat to try out.
The term is "pointer". But that's another emotion-laden term that scares
off the ignorant who think that "pointers are bad" because C lets you run
loose with them, while Java constrains their use to reasonable safety.
In short, Java does have pointers and does not have call by reference,
but you will hear heated arguments against both of those assertions, which
are, as you say, just arguments of terminology, not substance.
It can if the tuple is defined as a value type. Objects of value types use
copy, not reference semantics, and are not allocated on the heap, unless
this is necessary to pass them to a routine that is expecting an object
reference. Another example of a language that supports value types is Eiffel.
David Hopwood
david....@lmh.ox.ac.uk
In addition to Python's Tuples there are perl's array returning functions. An
oft-used perl builtin function is timelocal() which can be call thusly:
($second,$minute,$hour,$date,$month,$year,$weekday,$yday,$dst) = localtime();
it is more compact to use a single @array though such as:
@time = localtime;
in which case $second = $time(0);
Lots of folks do dislike perl's basic $scalar, @list, and %hash types though -
punctuation represents singular vs. multiple (or Tuple if you prefer :)
Peter Prymmer
pv...@lns62.lns.cornell.edu
It is truly call by reference:
SomeClass foo(AnotherClass a) {
a.uglySideeffect_change_my_state("Please document that");
/* This changes the state of x when called with foo(x) !! */
a = somethingElse();
/* this statement could be optimized out if somethingElse()
had no sideeffects,
if somethingElse() creates a new object, this object will
be garbage collected ....
the reference itself is handed by value ...
the statement "a = somethingElse();" says:
now a should no more reference what it does before, but it
should reference "somethingElse()".
By no way You are allowed to contact any memory location
by Yourself in a garbage collected system !
*/
}
Maybe it is good to come from lisp, ml, scheme to java ... or to STAY
with lisp, ml, scheme because this confusion can bite You again and
again, even if You really understood it.
--
Viele Gruesse,
Fritz Heinrichmeyer FernUniversitaet Hagen
FAX: +49 2371/566236 LG Elektronische Schaltungen
EMAIL: fritz.hei...@fernuni-hagen.de Frauenstuhlweg 31
PHONE: +49 02371/566-243 58644 Iserlohn (Germany)
WWW: http://ES-sun2.fernuni-hagen.de
-----BEGIN PGP PUBLIC KEY BLOCK-----
Version: 2.6.2i
mQCNAzGZwoAAAAEEAJV5CMQiOzh9dOUKtKexl9VOxkxqkS0DbwZcqhmgPCkeYEl3
5a9xi6BMncIs2haDnOKxULXODMRsXvtjFuqNGXZuKZL5k7HQE4+HC6hSAWdrAYtg
mgXlicrq3OPMgadQ6mQYzEVC7lGT3jR7RyOrpPdlUOuCHGxMkyXeE8dj+s0FAAUR
tCRmcml0ei5oZWlucmljaG1leWVyQGZlcm51bmktaGFnZW4uZGU=
=auQB
-----END PGP PUBLIC KEY BLOCK-----
I guess you have a different meaning of "Call by Reference" than I do.
I would say it is "Call by Reference" if and only if
a = somethingElse();
has an effect on the outside object.
>Maybe it is good to come from lisp, ml, scheme to java ... or to STAY
>with lisp, ml, scheme because this confusion can bite You again and
>again, even if You really understood it.
I'm not saying it is not sometimes confusing in Java, just that it
still fits the normal (IMHO) CS definition of "call by value". BTW,
note that while Common Lisp, Scheme, and ML all use call by value, the
types of values vary. Lisp and Scheme (and Dylan and Smalltalk) values
are normally references for complex objects (just like Java). So just
like in Java, assigning a new value to the local object has no effect
on the outside object. But the reference can have subcomponents or
references to OTHER objects, which can be changed. ML, OTOH, goes to a
lot of work to truly make side effects impossible unless you use a
special kind of variable.
Cheers-
Java passes references by value.
Marty Hall wrote:
[snip]
> What makes this confusing is that Java uses the term "reference" for
> what it passes for the values of non-primitive objects (ie
> "references" here are pointers with restricted types of operations).
> Whether Java uses call by reference or call by value is independent of
> the kinds of values Java uses.
>
> Point: "call by reference" and Java "references" are two different
> things.
> - Marty
>
> Java Resources: <http://www.apl.jhu.edu/~hall/java>
(In practical terms, this means you can *modify* the object referenced
to, but you can't change the reference to point to a *different* object.)
-- Alastair
---------------------------------------------------------------------
Alastair Mayer The above is not intended to represent
mailto:a...@bix.com the opinion of US West, CTG, BIX, etc...
This is true. The only unused keywords still in the language are const,
goto, and transient (which is parsed as a field description, but is
not implemented in the VM).
Ken
: >If you get user-defined value types, and genericity (all of which
: >ought to come into Java), then you almost get tuples for free, as a
: >user-defined class.
: >
: >Sather does it.
: I don't know Python or Sather. But in the languages I've used that let
: you return multiple values directly on the stack (Lisp and Dylan), one
: of the most common uses was to avoid generating garbage. Ie if you
: wrap two return values into a data structure and then the calling
: function unwraps them and throws away the data structure, you can
: generate a pretty lot of garbage. I don't see how tuples as a
: user-defined class solve this problem.
Single instantiations of user-defined *value types*,
in contrast to objects of reference type, are generally
not heap allocated and hence do not become garbage requiring collection.
: - Marty
: Java Resources: <http://www.apl.jhu.edu/~hall/java>
It is call by reference because changes to the state of the object
originally pointed to by a are reflected to all who have reference
to that object. If you change what a points to (or references if you
prefer) it doesn't change the semantics.
----------------------------------------------------------------
Jeffrey L. Straszheim <mailto:jef...@shadow.net>
Systems Engineer
CPT of South Florida <http://www.cpt-florida.com>
----------------------------------------------------------------
Any opinions or recommendations are those
of the author and not of his employer.
Thank you for this simple and beautiful explanation. I'm starting to think
that for those of us coming from a "Lisp background" this has been so clear
that it is actually difficult to understand why others don't "get it", while
for those coming from "C++ background" it seems harder because the language
(C++ that is, and some others) really allows you to choose between types of
parameter passing, whereas Lisp and Java do not allow you to choose (not of
course including the confusion Lisp macros sometines cause :-).
- Ora Lassila
Nokia Research Center / Boston
Does this mean that if I pass an object of, say, the Integer or Float type, I
can modify the value of the Integer or Float inside the method? I heard that
even though Java does pass by reference, one cannot modify the value of the
reference inside a method and that the only way to get around this is by using
a trick involving arrays.....
Is this true?
thanks,
Ed.
--
Edward A. Shnekendorf <eshn...@cmr.gov>
Software Engineer, Center for Monitoring Research
<http://www.wam.umd.edu/~eshneken>
the classes Integer and Float define their value fields as being "final":
once initialized, they cannot be modified. You can get around this by
defining your own class where the value is not final:
class myInteger {
int value;
void myInteger(int new_value) {
value = new_value;
}
int get() {
return value;
}
void set(int new_value) {
value = new_value;
}
}
now you can use the methods to change the value, or just reach inside
with dot notation and change it directly;
myInteger i = new myInteger(3);
myInteger j = i;
i.value += 1;
System.out.print(j); // prints 4
I hope this makes it clearer.
Yes, one can change the object passed, however, in your example this
isn't possible since Integer, Float, etc are immutable.
--
\ The _____
\ /\ /idget
\ \/ \/ _______ David Zimmerman The Widget Workshop
\ /\ /orkshop dz...@widget.com 1143-I Executive Circle
\/ \/ Inc. 919 481 3352 Cary NC 27511
--
You cannot think about thinking, without thinking about thinking about something
-- Seymour Papert
: So Objects are passed by reference - not by value. Primitive types
: are passed by value.
: This is important, especialy for those coming from C/C++:
: // mind my incorrect C code...
: typedef struct X { /* a bunch of fields */ };
: void f1(X x) { }
: void f2(X *x) { }
: When I pass an X to f1 it will be expensive.
: When I pass a pointer (reference) to an X to f2 it is cheap.
: If I'm being impersise feel free to correct me...
: ..darcy
the funny thing about pointers is that a pointer is not always a pointer!
how do i know that my computer always lets me access memory directly?
the macintosh only lets u use pointers to pointers. that is, there is always
a level of indirection between you and your data. window's improves
the performance (i think) my using Lock and Unlock. when memory is
unlocked it can move, and you only get a pointer to it when it is fixed.
another thing that might be interesting to note is that Pascal had a
"with" statement which effectively put the address of an accessed
structure into a register so that all of the members of the structure
were simple offsets to this register. i was looking at what i considered
a tight loop in C, and found that A->x = A->x + B->x caused the compiler
to load the address registers for each "->" i put in the statement.
hence, if there are a large number of "->"'s in your code, it would
speed up things to use local varaibles.
as systems become bigger, i would imagine that this sort of thing
will be hard to get a handle on? (GMEM!)
Personally the discussion here showed that the implementation
technique of "call by reference" is easily confused with
the semantic idea of an "in-out" parameter.
--
dick botting http://www.csci.csusb.edu/dick/signature.html
Disclaimer: CSUSB may or may not agree with this message.
Copyright(1996): Copy freely but say where it came from.
I have nothing to sell, and I'm giving it away.
> the funny thing about pointers is that a pointer is not always a pointer!
> how do i know that my computer always lets me access memory directly?
> the macintosh only lets u use pointers to pointers. that is, there is always
> a level of indirection between you and your data. window's improves
> the performance (i think) my using Lock and Unlock. when memory is
> unlocked it can move, and you only get a pointer to it when it is fixed.
>
Hi
Just a little note for the books. On the Macintosh you can either
allocate memory with direct or indirect pointers. The chunks pointed to
by direct pointers are not moveable by the system, but the indirect are
(if they aren't locked).
With regards, Johan Dahl