Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Java > call by reference

Reply
Thread Tools

call by reference

 
 
rosty
Guest
Posts: n/a
 
      07-02-2005
I know there is no "call by reference" in Java. But please help me
convince two of my colleagues. We started learning Java about one
month ago, and they just don't believe me when i try to explain that
there is a confusion when passing reference types as an argumetn to a
function.

Please help. A link maybe to official documentation?

TIA
 
Reply With Quote
 
 
 
 
Chris Smith
Guest
Posts: n/a
 
      07-02-2005
rosty <(E-Mail Removed)> wrote:
> I know there is no "call by reference" in Java. But please help me
> convince two of my colleagues. We started learning Java about one
> month ago, and they just don't believe me when i try to explain that
> there is a confusion when passing reference types as an argumetn to a
> function.
>
> Please help. A link maybe to official documentation?


Well, the "official" reference would be JLS section 15.12.4.5, which
states:

Now a new activation frame is created, containing the target
reference (if any) and the argument values (if any), [...]

This can be verified experimentally:

class Test
{
private static void change(String s)
{
s = "New";
}

public static void main(String[] args)
{
String a = "Old";
change(a);
System.out.println(a);
}
}

This, of course, will print "Old" rather than "New", thus proving that
Java passes by value, even for reference types.

Most of the time, though, people who object to this fact *do* understand
the behavior of Java, and just have a fuzzy definition of "pass by
reference". When pressed, they will generally degrade to saying that
the meaning of "pass by reference" is language-specific, thus creating a
circular argument that you can't possibly disprove. Hopefully, they
will later come to their senses.

In any case, you might start by asking them whether the following
examples demonstrate pass by reference:

Example 1, in C:

void change(int *s)
{
*s = 7;
}

int main(int argc, char *argv[])
{
int a = 42;
change(&a);
printf("%i\n", a);

return 0;
}

Example 2, in Java:

import java.util.*;

class Test
{
private static Map m = new HashMap();

private static void change(String key)
{
m.put(key, "New");
}

public static void main(String[] args)
{
m.put("a", "Old");
change("a");
System.out.println(m.get("a"));
}
}

The answers to these two questions will give you an idea of what this
person thinks that "pass by reference" really means.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
Reply With Quote
 
 
 
 
George Cherry
Guest
Posts: n/a
 
      07-02-2005

"Chris Smith" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed).. .
> rosty <(E-Mail Removed)> wrote:
>> I know there is no "call by reference" in Java. But please help me
>> convince two of my colleagues. We started learning Java about one
>> month ago, and they just don't believe me when i try to explain that
>> there is a confusion when passing reference types as an argumetn to a
>> function.
>>
>> Please help. A link maybe to official documentation?

>
> Well, the "official" reference would be JLS section 15.12.4.5, which
> states:
>
> Now a new activation frame is created, containing the target
> reference (if any) and the argument values (if any), [...]
>
> This can be verified experimentally:
>
> class Test
> {
> private static void change(String s)
> {
> s = "New";
> }
>
> public static void main(String[] args)
> {
> String a = "Old";
> change(a);
> System.out.println(a);
> }
> }
>
> This, of course, will print "Old" rather than "New", thus proving that
> Java passes by value, even for reference types.


Chris, I'm afraid your example will give rosty the wrong
notion that a called method can't change an object
when you pass the method the value of a reference
variable referring to the object? For example, rosty,
take a look at this:

class TestPassByValue2 {
private static void change(int[] a) {
a[0] = 4;
a[1] = 5;
a[2] = 6;
}

public static void main(String[] args) {
int[] intArray = new int[]{1, 2, 3};
change(intArray);
for (int i : intArray) {
System.out.print(i + " "); //Prints 4 5 6
}
}
}

George Cherry


 
Reply With Quote
 
Chris Smith
Guest
Posts: n/a
 
      07-02-2005
George Cherry <(E-Mail Removed)> wrote:
> Chris, I'm afraid your example will give rosty the wrong
> notion that a called method can't change an object
> when you pass the method the value of a reference
> variable referring to the object?


Only if rosty doesn't understand what's going on... which he said he
did. The point is that assigning to the formal parameter does not
affect the value of the actual parameter. In your code:


> private static void change(int[] a) {
> a[0] = 4;
> a[1] = 5;
> a[2] = 6;
> }


In this case, you never assign to the formal parameter, so it doesn't
even matter if the parameter passing is by reference or by value. The
parameter just happens to identify some shared state, and you've
modified the shared state. This is exactly the same situation as my
"example 2" in the original post, and it doesn't demonstrate pass by
reference.

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
Reply With Quote
 
Tor Iver Wilhelmsen
Guest
Posts: n/a
 
      07-02-2005
http://www.velocityreviews.com/forums/(E-Mail Removed) (rosty) writes:

> Please help. A link maybe to official documentation?


Java passes everything - primitives and object "references"/pointers -
by value.

Java does not have anything like C++'s reference concept. If you come
from C++, then Java does not have "pass by reference". C# does have it
though, but explicitly: In C# "struct"-originated objects are put on
the stack and passed by value, unless you use the "ref" keyword in the
method parameter declaration.
 
Reply With Quote
 
rosty
Guest
Posts: n/a
 
      07-02-2005
Thank you all! That's exactly what i was saying, but they would just not
listen. I'l show them this on monday. We'll see.
"Chris Smith" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed)...
> George Cherry <(E-Mail Removed)> wrote:
>> Chris, I'm afraid your example will give rosty the wrong
>> notion that a called method can't change an object
>> when you pass the method the value of a reference
>> variable referring to the object?

>
> Only if rosty doesn't understand what's going on... which he said he
> did. The point is that assigning to the formal parameter does not
> affect the value of the actual parameter. In your code:
>
>
>> private static void change(int[] a) {
>> a[0] = 4;
>> a[1] = 5;
>> a[2] = 6;
>> }

>
> In this case, you never assign to the formal parameter, so it doesn't
> even matter if the parameter passing is by reference or by value. The
> parameter just happens to identify some shared state, and you've
> modified the shared state. This is exactly the same situation as my
> "example 2" in the original post, and it doesn't demonstrate pass by
> reference.
>
> --
> www.designacourse.com
> The Easiest Way To Train Anyone... Anywhere.
>
> Chris Smith - Lead Software Developer/Technical Trainer
> MindIQ Corporation



 
Reply With Quote
 
Lasse Reichstein Nielsen
Guest
Posts: n/a
 
      07-02-2005
(E-Mail Removed) (rosty) writes:

> I know there is no "call by reference" in Java. But please help me
> convince two of my colleagues.


First, you must agree what "call by reference" means. The traditional
meaning is the passing of an "l-value". Assume for a second that
this function (in some unknown language) was called using
call-by-reference:
---
function cbrFunc(ref int x) {
x = 42;
}

int y = 37;
cbrFunc(y);
print(y); // prints 42.
---

That is, with call-by-reference, you pass a reference, not a value,
and you can change the value at the end of that reference. In this
example, the "y" and "x" variables are the same reference (also called
aliasing), and changing the value of one also changes the value of
the other.

With call-by-value, assigning a new value to a variable will never
change the value of another.

Now check what Java does. In no case will it allow you to take
the reference out of a variable, so that its value can be changed
without using the variable itself.

/L
--
Lasse Reichstein Nielsen - (E-Mail Removed)
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
 
Reply With Quote
 
Dale King
Guest
Posts: n/a
 
      07-02-2005
Chris Smith wrote:
> rosty <(E-Mail Removed)> wrote:
>
>>I know there is no "call by reference" in Java. But please help me
>>convince two of my colleagues. We started learning Java about one
>>month ago, and they just don't believe me when i try to explain that
>>there is a confusion when passing reference types as an argumetn to a
>>function.
>>
>>Please help. A link maybe to official documentation?

>
> Most of the time, though, people who object to this fact *do* understand
> the behavior of Java, and just have a fuzzy definition of "pass by
> reference". When pressed, they will generally degrade to saying that
> the meaning of "pass by reference" is language-specific, thus creating a
> circular argument that you can't possibly disprove. Hopefully, they
> will later come to their senses.


Actually I find that more often it is not understanding the difference
between the object living on the heap and the variable that refers to
it. When people say objects are passed by reference they are showing
this confusion.

Here is the canned response I put together on the subject:

Question:
Does Java pass objects by reference or by value?

Answer:
Since it makes no sense to begin any argument without agreed upon
defintions let's formally define our terms. I will use abstract
pseudocode to keep the issue from being clouded by the idiom of a
particular language. The source of my information is the book
"Advanced Programming Language Design" by Raphael A. Finkel.

For those unfamiliar with the term below an L-value is an expression
that can appear on the left side of an assignment statement. It is
basically a way to address where a variable is stored. Variables
and other ways to refer to locations in memory are L-values. Most
expressions are not L-values, e.g. ( x * 2 )

We assume the presence of a procedure named f that takes a formal
parameter s. We call that function giving it an actual parameter g.

The calling code:
f( g )

The function:
procedure f( s )
begin
-- body of the procedure
end;

There are several parameter passing semantics that have been
proposed or used:

value
The value of the actual parameter is copied into the formal
parameter when the procedure is invoked. Any modification of
the formal parameter affects only the formal parameter and
not the actual parameter. This is the most common form of
parameter passing and is the only one provided in C and Java.

result
The value of the formal parameter is copied into the actual
parameter when the procedure returns. Modifications to the
formal parameter do not affect the formal parameter until the
function returns. The actual parameter must be an L-value. It
is usually invalid to pass the same L-value to more than one
result parameter, but the compiler cannot always detect this.
The best example of this is out parameters in CORBA.

value result
Combination of value and result semantics. The best example of
this are inout parameters in CORBA.

reference
The L-value of the formal parameter is set to the L-value of the
actual parameter. In other words, the address of the formal
parameter is the same as the address of the actual parameter. Any
modifications to the formal parameter also immediately affect the
actual parameter. FORTRAN only has reference mode (expressions are
evaluated and stored in a temporary location in order to obtain an
L-value). C++ has reference parameters by putting a & before the
formal parameter name in the function header. Reference mode can
be simulated in C using pointers and adding the & to the actual
parameter and dereferencing the formal parameter within the
function.

readonly
Can use either value or reference mode, but modification of the
formal parameter is forbidden by the compiler.

macro
name
These two have been used in the past, but are very much out of favor
because they are confusing and difficult to implement. Therefore I
won't bother trying to explain them.

Now that we have some definitions of terms we can return to the
question. Does Java pass objects by reference or by value?

The answer is NO! The fact is that Java has no facility whatsoever
to pass an object to any function! The reason is that Java has no
variables that contain objects.

The reason there is so much confusion is people tend to blur the
distinction between an object reference variable and an object
instance. All object instances in Java are allocated on the heap
and can only be accessed through object references. So if I have
the following:

StringBuffer g = new StringBuffer( "Hello" );

The variable g does not contain the string "Hello", it contains a
reference (or pointer) to an object instance that contains the
string "hello".

So if I then call f( g ), f is free to modify its formal parameter s
to make it point to another StringBuffer or to set it to null. The
function f could also modify the StringBuffer by appending " World"
for instance. While this changes the value of that StringBuffer, the
value of that StringBuffer is NOT the value of the actual parameter.

Imagine for instance if I set g to null before passing it to f. There
is no StringBuffer now to modify and f can in no way change the value
of g to be non-null.

The bottom line is Java only has variables that hold primitives or
object references. Both are passed by value.

--
Dale King
 
Reply With Quote
 
Mike Schilling
Guest
Posts: n/a
 
      07-02-2005

"rosty" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed) om...
>I know there is no "call by reference" in Java. But please help me
> convince two of my colleagues. We started learning Java about one
> month ago, and they just don't believe me when i try to explain that
> there is a confusion when passing reference types as an argumetn to a
> function.
>
> Please help. A link maybe to official documentation?



The best discussion of this I know of is at
http://www.yoda.arachsys.com/java/passing.html .


 
Reply With Quote
 
George Cherry
Guest
Posts: n/a
 
      07-02-2005

"Chris Smith" <(E-Mail Removed)> wrote in message
news:(E-Mail Removed).. .
> rosty <(E-Mail Removed)> wrote:
>> I know there is no "call by reference" in Java. But please help me
>> convince two of my colleagues. We started learning Java about one
>> month ago, and they just don't believe me when i try to explain that
>> there is a confusion when passing reference types as an argumetn to a
>> function.
>>
>> Please help. A link maybe to official documentation?

>
> Well, the "official" reference would be JLS section 15.12.4.5, which
> states:
>
> Now a new activation frame is created, containing the target
> reference (if any) and the argument values (if any), [...]
>
> This can be verified experimentally:
>
> class Test
> {
> private static void change(String s)
> {
> s = "New";
> }
>
> public static void main(String[] args)
> {
> String a = "Old";
> change(a);
> System.out.println(a);
> }
> }
>
> This, of course, will print "Old" rather than "New", thus proving that
> Java passes by value, even for reference types.


rosty:

The following code, of course, prints "New" rather than "Old".
It's important to realize that passing the value of a reference
variable (which points to an object on the heap) allows the
called method to change the object on the heap. But, of course,
the called method can't change the value of the caller's
actual parameter (which continues to point at the same object
on the heap). But note that String objects are immutable, so
the object pointed to by "a" in Chris's example can't be
changed--ever. I wonder therefore whether Chris's example
is, well, well, pedagogically effective??? : o )

class TestPassByValue3 {
private static void change(StringBuilder s) {
s.replace(0, 3, "New");
}

public static void main(String[] args) {
StringBuilder a = new StringBuilder("Old");
change(a);
System.out.println(a);
}
}

George W. Cherry


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Call by value vs. Call by reference Saeed Amrollahi C++ 10 07-15-2008 09:05 PM
difference b/w call by reference and call by pointer ravi C Programming 10 02-23-2007 10:57 AM
asp.net 2005 question re: "reference to a non-shared member requires an object reference" ce ASP .Net 1 06-23-2005 09:15 PM
web reference interfering with reference to component Dude ASP .Net 0 11-09-2004 11:53 AM
How to tell if a reference is project or file reference from within the IDE? Darren ASP .Net 0 10-11-2004 12:51 AM



Advertisments