Who modified my local variable?

Bryan Sant bryan.sant at gmail.com
Tue Jun 13 09:13:35 MDT 2006

On 6/12/06, Michael L Torrie <torriem at chem.byu.edu> wrote:
>Methinks Java's implicit pass by reference, and
> apparent lack of statically allocated objects, has poisoned a lot of
> programmers thinking.

What?  No mention of C# or a zillion other 4GL that do the same thing
:-)?  When moving back and forth between Java and C++ this is an
oddity.  Or if you learned to program in Java, but are writing
something in C++, you'll expect things to work differently (wrongly
from a C++ programmers perspective).  I agree that this can get

But just to clear things up.  Java doesn't pass by reference
implicitly.  It ALWAYS passes by value.  So when you pass any
primitive value, it works just like you would expect in C/C++ -- it
makes a copy of the var passed into a function (be it a byte, char,
short, int, double, etc.).  However, when you pass an object REFERENCE
into a function, it happily copies the reference (4-byte pointer on a
32-bit arch) and does not make a wasteful memory copy of object data +
vtable pointers.  And since the Java heap + garbage collector works
essentially like a stack, you always get the benefit of a stack even
when allocating on the "heap".  It's not quite that simple, there's a
lot of multi-generational GC  magic, but it's typically that
efficient.  Anyway, when dealing with all but the most trivial
objects/structs in C/C++ you typically pass those objects around by
reference or pointer anyway.  So the approach in Java and C++ really
isn't that different after all.

BTW if you really want a copy of an object, you can use a copy
constructor, or implement the clone() method.

As far as statically allocated objects, Java does have theses:

public static String bob = "What do you get when you spell bob backwards?";

There you go.  A static object -- allocated at startup and never again.


More information about the PLUG mailing list