pass by reference

R

Roedy Green

The objects are indeed passed by reference.

The JLP smacks you down for claiming it does. Did you ever see the
Monty Python sketch about the Bulgarian-English phrase book?
 
R

Roedy Green

but i can't help, String is a object, so a reference should be the one
passed, and why we can not update the field in the String object? and
then where is the field of the String?

The String class has no methods to change its internal fields. It is
immutable. So the callee, or anyone else that matter, can't change the
contents of a String object.

The caller has a local reference to the String. Java is designed so
the callee can't possibly change it. This was a language design
decision to create safer code based on years of experience with
languages that did allow it. You don't have to worry about side
effects of callees as much when reading code.
 
R

Roedy Green

Yes, I was wrong in my

public void myFunc(String s) {
s = "123";
}

because that compiles exactly as

public void myFunc(String s) {
s = new String("123");
}

Not quite. The first points s to a string constant sitting in the
literal pool. The second pointlessly creates a copy of the string on
the heap and points s to that.

See http://mindprod.com/jgloss/newbie.html
 
R

Roedy Green

Local copies will be made of the int and of the reference, but not of the
object. Let's say these local copies are stored in 0x4000 and 0x5000:

Another way of saying this that may make more sense to people with an
assembler, FORTH or other low level language background.

Primitive arguments are evaluated and pushed to the stack. References
to objects are pushed as 32 or 64 bit addresses/references to the
stack. The callee uses these much like local variables in its stack
frame, and pops them off and discards them on return. Thus changes to
the parameter variables are not reflected in the caller's variables.
 
R

Roedy Green

The most common pattern is just to use an array to pass the object
reference.
it is also the most commonly frowned on approach.

Returning an Object[] of kitchen sink item is like using machine
language in terms of type safety and ensuring documentation on what
goes in which slot is accurate and up to date.

For any but one-shot programs, I try to avoid that technique. When
you have an IDE like IntelliJ Idea to crank out those piddly little
return classes, the temptation to use Object[] is not as great.

Another approach is to use separate methods to retrieve the results,
perhaps after a call to compute them.
 
M

Mark Space

Roedy said:
The most common pattern is just to use an array to pass the object
reference.
it is also the most commonly frowned on approach.

Returning an Object[] of kitchen sink item is like using machine

And here I could have sworn I used String, not Object.
 
R

Roedy Green

Eeeeewwwww. I would definitely pass an array before I did something ugly
like that.

You could not do it otherwise for something as complex as Calendar.
 
A

Andreas Leitgeb

Patricia Shanahan said:
I don't think this one is just hairsplitting. The "objects passed by
reference" model does not explain what happens when the actual argument
is a null reference.

It's a question of point of view. JLS & jvm's point of view is surely
the one you've claimed, namely of "references by value". One level
down, we have memory-locations and registers that are written and no
concept of "passing things" at all, whereas one level above we focus
on objects that we want to "pass" on to methods, not really caring
about the exact mechanics.

With "pass me the sugar please", one doesn't explicitly state that the
sugar is actually in a jar, and that it's really the jar that will be
(hopefully) handed back to the one who asked for it.
 
A

Andreas Leitgeb

Roedy Green said:
The JLP smacks you down for claiming it does. Did you ever see the
Monty Python sketch about the Bulgarian-English phrase book?

JLP? Google's first hit is "Jamaica Labour Party" :)

I vill not bye diss record, because id is skredged!

Anyway, see my reply to Patricia's similar complaint.
 
M

Mark Space

Roedy said:

The problem here is that you're still using Object, and you don't have too.

Here's my version of passing a String and an int for reference:

void myFunc( String [] s, int [] i )
{
s[0] = "a new String";
i[0] = 42;
}

This requires less unpacking than your example, and there's no
auto-boxing either.

It's still not as pretty as I'd like, but I think one should only make
objects when a design calls for it. If all you need to do is mutate
some random value, pass in an array.

That's different from the case where your design actually calls for a
mutable object.

public class EmployRecord {
private String name;
private int employID;
void setName( String s ) { name = s; }
void setID( int id ) { employID = id; }
}

void myFunc2( EmployRecord e )
{
e.setName("a new Name");
e.setID( 42 );
}

This is a totally different idea, even though functionally myFunc and
myFunc2 do the same things.
 
M

Mark Space

Peter said:
[...]
Another approach is to use separate methods to retrieve the results,
perhaps after a call to compute them.

Eeeeewwwww. I would definitely pass an array before I did something
ugly like that.

Java now has variable arguments, which are just syntactic sugar for an
array.

I wonder if it would be worth while to add some syntactic sure for
references too.

void myMethod2( String & s, int & i )
{
s = "a new String"; // passed back to caller
i = 42; // passed back to caller
}

The Java compiler would have to insert something like:

{ // Boilerplate
if( s == null || s.length != 1 )
throw new RuntimeException();
}

for each argument, and similarly substitute "s[0]" for each use of "s",
and pack and unpack the variables on the caller's side, but it would
work, and be less error prone than having to do it all yourself.

*shrug*

It's not like I do this a lot anyway, so I don't see how much it truly
matters. It seems like only C++ and C programmers who are brand new to
Java have issues with Java's version of pass-by-reference.
 
C

Chris Smith

Andreas said:
With "pass me the sugar please", one doesn't explicitly state that the
sugar is actually in a jar, and that it's really the jar that will be
(hopefully) handed back to the one who asked for it.

Ah, but the problems arise when people try things precisely like the
example that started this thread. That is, try to write:

val = "New String";

and expect to see the changes in the calling stack frame. By the (fairly
universal) very definition of pass by reference, one would expect this to
work. One expects that using the formal parameter on the left-hand side
of an assignment will result in a change to the value of the actual
parameter.

That's not semantic games. It's a specific, observable, and testable
consequence that programmers would quite rightly expect from anything
called "pass by reference." In Java, it does not happen; therefore, it
is misleading to say "pass by reference" when talking about parameter
passing in Java.

There is certainly a higher-level view of what's going on. It's just
best to avoid using terms that have precise low-level meanings when
talking about things in terms of that higher-level view.

To belabor the point. Suppose, I had this:

public class Test
{
private HashMap m = new HashMap();

public static void change(String s)
{
m.put(s, "World");
}

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

Is this an example of pass by reference? If so, does the term retain any
meaning at all any more? If not, how does this differ from calling the
earlier code pass by reference?
 
A

angelochen960

hi Roedy,

I'd like to know more about this Intellij Idea and returned classes in
this case, any sample and use of Idea to achieve this?
Thanks,
 
A

angelochen960

Hi Guys,

Thanks for all the answers, it is very educational, finally you guys
help a C++ turned Java newbie understands this 'pass by reference'
java way, conclusion is, it does not exist:), i have to think in Java,
anyway i finally find the solution: return a array of objects. thanks,
till next time:)

Angelo
 
R

Roedy Green

I'd like to know more about this Intellij Idea and returned classes in
this case, any sample and use of Idea to achieve this?
Thanks,

It is just that intellij will let you compse a mini class very
quickly. It will build the constructor, getters and setters for you.

The final code is no different than you would write by hand, a
miniature holder class with fields for the various values you want to
return.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top