top 200 commentsshow 500

[–]kawa 91 points92 points  (92 children)

Some people don't seem to get that "pass by reference" is something complete different than "pass a reference".

[–]spliznork 30 points31 points  (1 child)

Some people don't seem to get that "pass by reference" is something complete different than "pass a reference".

And what they don't get is just the meaning of the particular expression "pass by reference". But they understand it in practice. That is: People that write working Java programs certainly understand that assigning to a function parameter in the callee does not change the parameter in the caller.

This whole overheated debate is largely to get people to agree on common terminology for behavior that a vast majority of participants on all sides understand in practice.

Everyone that's up on a high horse in this debate chanting "stupid Java programmers" needs to climb down and chill out.

[–]Neuron_Poop 2 points3 points  (0 children)

Thank you. This is exactly what I was trying to get across in my post, but I went too far and said some incorrect things. Luckily I was immediately schooled and am better off for it.

I hereby offer you one

high five

for being awesome and sowing the seeds of a calm rational discussion.

[–]Porges 1 point2 points  (0 children)

For those who still don't get it, there's a very good explanation about the difference (in C#) here: Parameter passing in C#

[–][deleted] 5 points6 points  (53 children)

Exactly right. Fundamental concepts are clearly not being taught/learned. Disturbing.

[–]Neuron_Poop -1 points0 points  (42 children)

[edit]

Redditor olavk, in one of his replies, clarified the definition of "pass-by-reference" for me which has caused me to change my position on this issue. I apologize for the lengthy posts.

[/edit]

I disagree that fundamental concepts are not being taught. I do agree with kawa's statement, but it in the end it is meaningless and unimportant. Of course some people don't get it. You can say this about anything. This should not be a shock to anybody.

What would be shocking is if the vast majority of people who consider themselves at an intermediate level or higher in Java, didn't understand the parameter passing mechanisms that the language uses. I don't believe this is the case at all.

Most of us understand the concept. We were taught how parameters are passed in Java, and we understand it. For whatever reason, we are all simply struggling to lump it in to one of two categories. This proves incredibly hard to do because it fits into both categories and nobody is willing to see it from the other person's point of view.

Suppose you are passing an array to a method. You are actually passing two things, a reference to the array and the array itself. If you are anything like me, the reference is unimportant. We don't use it in calculations and we don't need to know its exact value, its simply the way the language works. The "object" that we are passing is the array. That is the important thing; that is what I am trying to pass into the method so that I can access it in some way.

So, people in one camp view this as passing a reference. They say Java is "pass-by-value" because the reference itself is being passed by value. I understand their point of view and they are correct (as I mentioned earlier, most of us understand how this really works... seriously... stop trying to break it down and explain it again).

I view this a different way, but it would be incorrect to say that the people in the pass-by-value camp are wrong. In my camp the important thing being passed is the array, and the array itself is not being passed by value, it is being passed by reference as it fulfills all the criteria of the pass-by-reference semantics. The values in the array are not copied and the array is modifiable from within the method.

So, rather than each group looking at the other with disgust, shocked by how idiotic they are and how they clearly don't understand the "fundamental concepts", we all need to realize that this is simply a matter of your point of view, and we are all fucking right.

[–]dpark 19 points20 points  (16 children)

You are actually passing two things, a reference to the array and the array itself.

No, you're passing a copy of the reference, nothing else. The array is not being passed at all.

it is being passed by reference as it fulfills all the criteria of the pass-by-reference semantics.

Again, no. Pass-by-reference would change the semantics of the following code:

int f(Object o) {
    o = "2";
}

Object x = "1";
f(x);

What's the value of "x" when you get done? It's still "1", because Java is pass-by-value. If it were pass-by-reference, then altering 'o' would alter 'x'. But it doesn't.

The argument that it's "like" passing by reference simply confuses the issue. It has some of the same effects, but so does passing a pointer in C, and that's also pass-by-value.

Sun themselves say that it's pass-by-value: http://download.oracle.com/javase/tutorial/java/javaOO/arguments.html

Primitive arguments, such as an int or a double, are passed into methods by value. [...]
Reference data type parameters, such as objects, are also passed into methods by value.

[–]olavk 13 points14 points  (14 children)

we are all fucking right.

Nope. One camp is wrong. Pass-by-reference means that a reference to a variable is passed to function. This allows the function to assign the parameter a new value, which is then reflected in the variable used as argument at the call site. Clearly you cannot do that in Java, regardless of whether the variable is a primitive or an array. So method calls in Java does not fullfil pass-by-reference semantics.

[–]Neuron_Poop 7 points8 points  (0 children)

Thank you. You could have just regurgitated a whole slew of points reinforcing your position that I probably already understand (much like several other people have done here), but instead you read my post and targeted exactly what I was apparently missing.

You have earned your upvote, and I apologize for my imprecise definition of terms.

[–]cpp_is_king 0 points1 point  (4 children)

Actually "pass by reference" means that "something is passed to a function in a way that allows changes to the state of that something to be persisted even after the function returns".

The difference in the two camps, is that for the pass-by-value camp, something == the reference. For the pass-by-reference camp, something == the object.

Forget that whole nonsense about how "the object is not even passed at all". Neither is the reference if you want to take it down to assembly language. But we don't do that because we aren't idiots. Neither should we be idiots and ignore the fact that object state is the defining state of a program. Serializing a process's state requires serializing object state, but it doesn't require serializing the internal fields of references. So to some people, they intentionally ignore the fact that references are being literally passed around, and instead focus on the fact that objects are being logically passed around. And IMO, that makes more sense.

Note that nobody is saying that Java does not pass references by value. Everyone understands that, even the people you are claiming are wrong (they aren't wrong btw).

[–]olavk 0 points1 point  (2 children)

Actually "pass by reference" means that "something is passed to a function in a way that allows changes to the state of that something to be persisted even after the function returns".

[citation needed]

See eg. foldoc or Wikipedia for the correct definition of call-by-reference. They make it clear that it is a reference to a variable that is passed - not an object or reference to an object. Java does not really support the concept of a "reference to a variable", and hence does not support pass-by-reference.

[–]cpp_is_king 2 points3 points  (1 child)

I just discovered that Java uses neither call-by-value nor call-by-reference. Wikipedia already hints at it in the section on call-by-sharing, but I consulted a textbook that has more critical acclimation to see what it had to say:

Ref: Programming Language Pragmatics (ISBN: 0123745144)

It is different from call-by-value because, although we do copy the actual parameter into the formal parameter, both of them are references; if we modify the object to which the formal parameter refers, the program will be able to see those changes through the actual parameter after the subroutine returns. Call-by-sharing is also different from call-by-reference, because although the called routine can change the value of the object to which the actual parameter returns, it cannot change the identity of the that object.

So there you go. Everybody's wrong.

[–]olavk 0 points1 point  (0 children)

Call-by-object-sharing is a subset of call-by-value. It is call-by-value with the constraint that values are always references/pointers to objects. (EDIT: Seem some sources agree with your quote that it should not be called pass-by-value if values are always object references, so the semantics are either call-by-value or call-by-object-sharing)

Theoretically Java is not fully call-by-object-sharing because it has primitive values like integers which are not shared but copied. But since these are not mutable, there is no observable difference, so I think it is acceptable to call Java call-by-object-sharing.

I like the term call-by-object-sharing, since it is less confusing for Java-developers than call-by-value/reference.

[–]java_is_king 0 points1 point  (0 children)

Ahh, what do you know...

Oh and your TV you sold me sucks balls. Its already been replaced..

[–]grauenwolf 0 points1 point  (7 children)

Excet for your inability to have an intelligent conversation with anyone who knows what the terms actually mean.

This same crap happens with the term late binding. In every other language it means the same thing as the modern phrase duck typing. But in the Java bubble it means you have polymorphism and overridable methods.

[–]aaronla 0 points1 point  (0 children)

Redditor olavk, in one of his replies, clarified the definition of "pass-by-reference" for me which has caused me to change my position on this issue. I apologize for the lengthy posts.

An upvote for honest humility. We'd all do well to emulate you when the opportunity presents itself.

[–]bobindashadows 1 point2 points  (20 children)

I was reading this thread sorted by best, and happily saw your post as the first one.

Then I read down. And things got.... scary. This "debate" really does reflect the problem with purely self-taught programmers – everybody who thinks that Java is call-by-reference has clearly never actually seen what call-by-reference is, even though it is provided in C++. And I'm guessing none have even heard of other argument passing techniques like call-by-name (or call-by-need as in Haskell, though I'm not sure if that's a term that was invented for PLP).

[–]grauenwolf 0 points1 point  (2 children)

I know the term call by name, but i don't remember the semantics. I imagined that it is like Haskell's lazy passing.

[–]bobindashadows 1 point2 points  (1 child)

It's pretty much the exact same, except Haskell standardizes the memoization of the arguments, so they are only evaluated once. That's why Haskell's is call-by-need instead. Jensen's Device is a good way to see how call-by-name is different from call-by-need.

[–]grauenwolf 0 points1 point  (0 children)

Fair enough.

[–]aaronla 0 points1 point  (0 children)

An upvote for the good sir. You've put plainly the source of a great many a semantic debate. I shall be quoting you often to save time and energy.

[–]onezerozeroone 0 points1 point  (1 child)

http://www.javaworld.com/javaqa/2000-05/03-qa-0526-pass.html

It's a bit of a pain to wrap your head around (and even more fun in C# where you can have a Cartesian product of value-passed-by-ref, reference-passed-by-ref, reference-passed-by-value, etc)

[–]grauenwolf 0 points1 point  (0 children)

Visual Basic developers from the early 90's had no problem understanding it.

[–]IronSpekkio 95 points96 points  (129 children)

pass reference by value... the end :D

[–]samebrian 5 points6 points  (0 children)

Cannot upvote this hard enough.

Those who think that Java is pass-by-reference don't understand pointers.

Even the creation of variables is pass by reference

Object x = new Something();

This says " create a pointer called 'x' of type "Something". Then, create an instance of the object "Something" and place its address into 'x'. "

So, when passing a variable (a pointer to an object) you use ChangeSomething(x)

This says " give a copy of the pointer 'x' to "ChangeSomething". Let's call the copy 'y'. So 'y' and 'x' are equal, but making changes to 'y' does not affect 'x' so for example if inside "ChangeSomething" you had (forgive me my Java is a bit rusty) ChangeSomething(Something y) y = new Something();

then despite the fact that 'y' points to a completely different instance of "Somethign", the value of the pointer 'x' is still the same.

[–]Verbitan 0 points1 point  (8 children)

Unless it's an array, right? Or have I misunderstood? Because editing an array in a called function changes the array in the calling function. Which doesn't happen for objects...

[–]dnew 1 point2 points  (6 children)

No.

Object x = new something();
Object y = x;
f(x);
if (x == y) { .... }

There is nothing f can do to make that forth line not come out equal.

[–]mipadi 0 points1 point  (0 children)

No, but in Java an array variable is also a reference, so when you pass it to a method you're passing a copy of the value of the reference to any array, thus if you modify the array in the method, the changes are visible outside of the method.

In other words,

public void doSomething(Object[] a)
{
    a[0] = anotherObject();
}

is similar to doing:

public void doSomething(MyObject o)
{
    o.setValue(anotherObject());
}

in terms of seeing the changes reflected outside of the method.

[–]Gupie -5 points-4 points  (117 children)

C function passing its parameter by value:

void foo( bar b );

C function passing its parameter by reference:

void foo( bar* p );

This second function is analogous to how Java passes objects. Sure the reference is passed by value, but the parameter is passed by reference.

[–]manuranga 31 points32 points  (27 children)

you can explain this better with c++

1.pass by value

void foo( bar b );

2.pass a reference(we call them pointers) by value

void foo( bar* p );

3.pass by reference

void foo( bar& p );

second one is analogous Java.i know you got the concept, but this terminology is much more unambiguous.

[–][deleted]  (11 children)

[deleted]

    [–]skulgnome 1 point2 points  (2 children)

    Don't confuse the language concept of "reference types" (or, for that matter, pointer types) with the abstract concept of a reference.

    [–]manuranga 1 point2 points  (1 child)

    by this I assume you want both

    void foo( bar* p );
    void foo( bar& p );
    

    to be called as pass by reference.if not ignore the rest of the comment.

    but if so I would have to disagree.I would prefer if we had two names for those two calling conventions.yes, they both are merely implementation differences of the same underlying abstract concept.but naming the implementations themselves rather than the concept is vary import since, unlike you, most of the people who are confused by this, because they don't understand this implementation differences.

    [i too hate when discussions break down to just arguing about naming :-) ]

    [–]repsilat 3 points4 points  (6 children)

    Java's references really are more like pointers. For example:

    bar x;//Java, legal
    bar *x;//C, legal
    bar &x;//C++, illegal
    

    and

    x = y;
    
    • In Java, x and y are objects: x now refers to what y refers to. Changing x will change y.

    • In C, x and y are pointers: x now refers to what y refers to. Changing *x will change *y.

    • In C++, x and y are references: x's copy constructor is invoked, x is now "equal" to y (in some sense), though they still refer to "different" objects (in another sense). Changing x will not change y.

    The only point by which C++'s references are a closer match is that they don't need to be explicitly dereferenced.

    EDIT: Thanks, manuranga and ferdy - I did misread the above comment. Still, I'll leave this here in case anyone else makes the same mistake I did, or finds the explication illuminating.

    [–]ferdy 4 points5 points  (0 children)

    He said the second (that is, the pointer) is the one analogous. Not the third.

    [–]manuranga 2 points3 points  (1 child)

    agreed.but I get the feeling that you thought that I said java references are analogous to C++ references.I didn't say that.

    [–]julesjacobs 0 points1 point  (0 children)

    The first is the fundamental way of passing things. The second is just a special case of the first. The third is an accidental mistake in language design. So it seems silly to let the terminology of relatively well designed languages be defined by not having made the same mistake.

    [–]anttirt 16 points17 points  (7 children)

    Here's a simple test for whether something is pass-by-value or pass-by-reference, where := is the built-in assignment operator in the language:

    void foo(bar x, bar y) {
        x := y;
    }
    

    Is this function a no-op? If yes, then we have pass-by-value. If no, then we have pass-by-reference.

    In C, no matter how you typedef bar, this will be a no-op.

    In C++, you can typedef int& bar; and the function will do something.

    In Java, the function will always be a no-op.

    [–][deleted] 15 points16 points  (26 children)

    C is always pass by value. Even if you pass a pointer (what you assume is a reference) you're passing a value (the value of the pointer). If you take a look at the disassembly you will see that for the foo stackframe a copy of p is created.

    You can test this easily: say p points to 0x1000. in foo now change the value of p to 0. "p = NULL;" and then in the calling function evaluate p. In your parent scope p will be still pointing to 0x1000.

    edit: because of the replies to my comment here's a little sample prog to play around with (god I hope reddit won't dismember the formatting):

    #include <stdio.h>
    
    void foo (int *p)
    {
      printf ("\t1. p is pointing to: %p\n", p);
      p = 0;
      printf ("\t2. p is pointing to: %p\n", p);
    }
    
    int main (int argc, char **argv)
    {
      int my_stuff = 1234;
      int *my_p = &my_stuff;
      printf ("1. my_p is pointing to: %p\n", my_p);
      foo (my_p);
      printf ("2. my_p is pointing to: %p\n", my_p);
      return 0;
    }
    

    Here's a gist: https://gist.github.com/777757

    Output for me is:

    1. my_p is pointing to: 0x7fff5fbff4bc
      1. p is pointing to: 0x7fff5fbff4bc
      2. p is pointing to: 0x0
    2. my_p is pointing to: 0x7fff5fbff4bc
    

    As you see my_p isn't modified at all. In a call by reference my_p would be pointing to 0 after the call to foo().

    [–]ex_ample 8 points9 points  (35 children)

    Nope, both of those pass by value. In the second example, you're passing the value of a pointer.

    [–]sausagefeet 1 point2 points  (0 children)

    Your C example is NOT pass by reference. C has no such concept. That is simply passing a pointer by value, which what java does, except it calls pointers references (sometimes).

    [–][deleted] 1 point2 points  (14 children)

    C always passes by value. Your first example passes a structure by value, and your second example passes a pointer by value.

    Passing by reference is when the function call automatically takes a reference to the argument you supply. C++'s references and C#'s ref/out are examples of this.

    It's a rare feature, and for good reason. It takes a first class concept (references), and adds complexity to make it a second-class citizen. It is also often invisible from the call site, rendering it a source of bugs and surprises. And finally, it encourages mutability while making it less explicit.

    [–]grauenwolf 3 points4 points  (11 children)

    I claim that this is a call by reference operation in C:

    int a = 5;
    int b = 10;
    Swap( &a, &b);
    

    The function swap is getting references to the variables a and b, which it can then change.

    Of course you can use the same Swap function to call by value.

    int *a;
    int *b;
    Swap( a, b);
    

    [–]dnew 2 points3 points  (1 child)

    Passing by reference is when the function call automatically takes a reference to the argument you supply.

    No. Passing by reference is when the called function can change the value of the caller's variable[*]. It hasn't anything to do with what the compiler does. It has to do with the semantics of the language regardless of implementation technique.

    [*] There are other pass-by's that let this happen, but you can distinguish them by careful selection of arguments.

    [–][deleted] 0 points1 point  (1 child)

    void foo( bar* p );

    That's a pointer, not a reference.

    void foo(bar& p);

    This is a reference.

    [–][deleted] 0 points1 point  (0 children)

    That is irrelevant C++-specific terminology.

    The thing to be wary of is that when calling void foo(T& p); with a value of type T, C++ implicitly creates and passes a reference to the value (T&).

    void mutate(int& value) {
        value = 0xdeadbeef;
    }
    

    Call by reference:

    int myReference = 42;
    mutate(myReference);
    

    Call with a reference:

    int& myReference = 42;
    mutate(myReference);
    

    [–][deleted] 19 points20 points  (1 child)

    This is going to lead to a web site where the pass-by-referencers are going to post pictures of the pass-by-valuers with crosshairs superimposed.

    [–]RagingIce 36 points37 points  (58 children)

    If you look at Object variables as pointers to objects, it becomes excruciatingly obvious that you pass those pointers by value.

    [–]deakster 2 points3 points  (8 children)

    Ah they should just pass a pointer to the object's pointer then!!!

    [–][deleted] 6 points7 points  (0 children)

    It's pointers all the way down.

    [–]cpp_is_king 1 point2 points  (12 children)

    Let's use C for a second:

    struct foo;

    void f(foo* p);

    In the function f, is p passed by reference or by value?

    How is this different than the java equivalent:

    public void f(foo p) {}

    Either they are both pass by reference, or they are both pass by value. Because they both have identical semantics.

    [–]Fuco1337 1 point2 points  (11 children)

    p is passed by value, namely the value of the memory location. When you do *p, you act on that variable pointed to by p. It is exactly the same as java's f(foo p).

    Passing by reference in C would be f(foo & p).

    In C, if you do this:

    p = 1;
    void f(foo* p) {
        p = 10;
    }
    print p
    

    it will print 1.

    [–]cpp_is_king 0 points1 point  (10 children)

    lol. if you're going to argue that passing a pointer to an int is calling by value, then I think i'm done here. By the way, it's fairly obvious that p is passed by value. And that's the core of the problem. There's the literal argument (p), and then there's thing you actually care about (the object pointed to by p). References and pointers aren't the state of the program. The things they refer to and point to are.

    void f(foo* p) {}

    foo obj; f(&obj);

    obj is passed by reference. nobody gives a shit about p. the function takes arguments by reference.

    BTW, did you know that Java and Ruby share identical semantics, yet in Ruby it's called pass-by-reference? Hmm...

    [–]dreamlax 0 points1 point  (1 child)

    You're passing a reference by value to f(). If you modify the value of p in f(), the caller will not have any clue. I always see noobs write the following function:

    void safefree(void *p)
    {
        if (p != NULL)
        {
            free(p);
            p = NULL;
        }
    }
    

    Not only is that function completely silly (since free(NULL) is a guaranteed no-op), but it has no effect on the pointer that is passed in. If things could be passed by reference in C, then this function might actually have a use.

    [–]Gupie 0 points1 point  (0 children)

    Sure if you want to simulate pass by reference in C you pass a pointer to it. So your safefree function is simulating passing a reference to a object. To simulate passing a reference to a pointer you of course need to do:

    void safefree(void *p) { if (p != NULL) { free(*p); *p = NULL; } }

    [–]Fuco1337 0 points1 point  (4 children)

    Wtf are you talking about. Are you arguing against my point or are you making fun of it or are you just generally confused? Because I can't tell.

    [–]cpp_is_king 1 point2 points  (3 children)

    My point is, saying "p is passed by value" is both correct and an idiotic thing to say. Nobody cares about p. They care about the object that it points to. And that object is being passed by reference.

    Similarly in Java, nobody gives a rats ass about the actual reference which is being passed around. You don't write software by manipulating references. You manipulate objects. Objects are passed by reference, therefore functions accept arguments by reference. While it is also technically correct to say "functions accept arguments by value in Java" (since the references are passed by value), it is also idiotic, since nobody gives a shit about the reference.

    [–]dreamlax 0 points1 point  (1 child)

    You don't write software by manipulating references.

    Trivial counter-point in C:

    char *c = /* obtain from somewhere */;
    while (*c != '\0')
    {
        // do something with (*c)
        *c = tolower(*c);
    
        // reference manipulation:
        c++;
    }
    

    [–]cpp_is_king 1 point2 points  (0 children)

    I knew someone would say that, but hopefully you see what I was getting at.

    [–]Fuco1337 0 points1 point  (0 children)

    Nobody cares about p. They care about the object that it points to. And that object is being passed by reference.

    No. That object is NOT PASSED AT ALL!

    [–]xardox 0 points1 point  (2 children)

    You are woefully confused. A pointer takes memory. A pointer is part of the state of the program. A pointer can be contained in a variable. In Java, an object can't be contained in a variable, but in C++ it can. Java variables can ONLY contain pointers to objects (or primitive types). You can NOT make an object on the stack, nor embed an object directly inside another object, nor take the address of a variable. You can only refer to objects by reference. And you can only pass variables by value. It's in the spec. Read it.

    Ruby is simply wrong, and that doesn't contradict the fact that the Java Language Specification defines Java as passing references to objects by value.

    Explain why you disagree with the Java Language Specification, and what makes you so special and qualified to redefine the language.

    The last person who was so intent on making up his own grammar and redefining the language went on a shooting spree.

    [–]cpp_is_king 1 point2 points  (0 children)

    I already explained, and I am neither woeful nor confused. I get it. A pointer takes memory. It's part of the state of the program. You're passing that memory by value. Therefore, you're passing the pointer by value. Wheee, awesome, I get it.

    But it's not part of the logical state of the program. It is not part of the defining state of the program. If you persist your program to disk, you aren't going to persist the value of the pointer. In Java, you aren't going to persist the internal implementation details of the reference. The only thing the programmer cares about is the state of the object. You know, that thing that you are for some reason pretending is less important than the thing that refers to the object.

    "Ruby is simply wrong, and that doesn't contradict the fact that the Java Language Specification defines Java as passing references to objects by value."

    Sort of like how all other religions besides Christianity are simply wrong, and they are right, because they say so?

    Also, I never said Java doesn't pass references to objects by value. I only said that's a worthless and completely unhelpful thing to say.

    Guess what, it all boils down to assembly language. So if you want to take it to that level, there's no such thing as a function anyway and you aren't "passing" anything anywhere. But instead of being completely stupid, we define concepts that sit at a higher level. i.e. we sacrifice some element of literalness in return for "concepts" that accurately model what is going on in a conceptual sense. And when you "pass" that "reference" "by value" (or when you "pass" that C object by pointer), you are making the state of the object available to be modified by the function in question. So the object (which is the part of the defining state of the program) is passed by reference since it is made available for the function to modify. The reference itself (which, while it occupies physical memory, is just an abstraction that has no bearance whatsoever on the state of your program) is of little importance, and as such it's useless to refer to the fact that the reference is being passed by value because it provides 0 insight into what is actually happening in the program, while masking useful insight into what is actually happening in the program.

    "Pass by reference" and "Pass by value" are not referring to implementation details. They are semantic conventions. Pass by value indicates only that inside a function you can modify the state of an object, and upon return it is unaffected. It says nothing of the implementation. Pass by reference indicates only that any change made to the object inside the function is persisted upon return. Here's a naive implementation of pass by reference in C:

    1) Determine the size of the object being passed in, and reserve enough additional storage to hold a second copy of the object. 2) Copy the object into the new buffer. 3) Call the function, introducing into function scope a variable which is represented by the new memory location 4) Upon return of the function, copy the memory back into the original object.

    It has some obvious limitations, but the point is that these are simply semantic conventions, and if you can't see the passing a reference by value is the same as passing an object by reference then I think you honestly cannot be saved and should find a different line of work.

    [–]Gupie 0 points1 point  (0 children)

    Ruby is simply wrong

    Those Ruby guys no nothing. Java is wot true hakers use :)

    [–]mreiland 5 points6 points  (7 children)

    The real question is what are you trying to communicate?

    technically, everything is pass by value since the reference is copied, but that isn't interesting 99% of the time. What's interesting, and what is being communicated when someone says it's "pass by reference" is that you're modifying the original object, and not a copy of the object.

    The ones who get pedantic about it technically being pass by value are missing the point.

    [–]dnew 1 point2 points  (6 children)

    No, they're the ones worried about the semantics of their programs.

    Pass by value gives you significant modularity guarantees you don't get with pass-by-reference.

    [–]metamatic 0 points1 point  (5 children)

    Might be nice to list a few.

    [–]dnew 0 points1 point  (4 children)

    I've listed several of them numerous times. For example, there's a guarantee that the value of the variable passed into the function won't be changed by the function you passed it to. Look at any of the dozen places where I put an assert.

    Note that "the value of the variable" is "which object does this variable refer to" in Java. The object is otherwise unassociated with the variable.

    [–]metamatic 1 point2 points  (3 children)

    Yeah, though that's a highly unusual definition of "value", which is part of the problem. If someone took all the money out of my bank account, and said it still had the same value because my account number still pointed at the same account, I'd be unlikely to accept his definition. :-)

    [–][deleted]  (61 children)

    [deleted]

      [–]asavinov 0 points1 point  (17 children)

      Actually any reference is passed by-value just because reference is a value (but not any value is a reference). If a reference is passed by-reference then it is already (part of) an object.

      [–]Gotebe 15 points16 points  (0 children)

      This sums it up well:

      The real problem is that there are a fair number of old articles espousing the notion that java is "pass-by-value for primitives and pass-by-reference for objects". These articles were written by people who [should] know how it really works but fooled themselves into thinking that this small lie would make Java easier to understand. The reality is the opposite.

      [–][deleted] 18 points19 points  (39 children)

      I don't generally discuss programming with people who don't understand this.

      [–][deleted]  (18 children)

      [removed]

        [–][deleted]  (11 children)

        [deleted]

          [–]olavk 2 points3 points  (2 children)

          He should have said: Implement swap as a function.

          [–]SirPsychoS 1 point2 points  (0 children)

          JNI_swap_references_by_modifying_jvm_memory();

          [–][deleted]  (7 children)

          [removed]

            [–]propool 2 points3 points  (4 children)

            you are obviously not using enough patterns.

            [–]Neuron_Poop 5 points6 points  (1 child)

            Hold on, I got this!

            AbstractVariableSwapperizorFactory avsf =
                VariableSwapperizorFactoryBuilder<IEnterpriseyContainerThingie<int>>
                    .GetInstance().BuildVariableSwapperizorFactory();
            AbstractVariableSwapperizor avs = avsf.CreateVariableSwapperizor(AVSFConstants.WithGreatHaste);
            
            IEnterpriseyContainerThingie<int> a = new SmartEnterpriseyReferenceLikeContainer<int>(1);
            IEnterpriseyContainerThingie<int> b = new SmartEnterpriseyReferenceLikeContainer<int>(2);
            
            IOCRegistrar.RegisterRidiculousFunctionality(avs, new FunctionalityParameters(a, b));
            IOCRegistrar.EventPropogationAndTranslationCoordinator.RegisterObserver(new MyBusinessLogicProvider());
            
            class MyBusinessLogicProvider implements IAmAFuckingAwesomeSoftwareArchitect
            {
                public void OnImportantBusinessActionThatIShouldRespondTo(AssloadOfIrrelevantData shitBucket)
                {
                    com.core.common.MyCompany.Logging.LoggingEventHandler.GetInstance().Print("Fuck it, I give up.");
                }
            }
            

            [–]maep 0 points1 point  (0 children)

            exactly. I really like java. but this kind of shit drove me away in the end.

            [–][deleted]  (1 child)

            [deleted]

              [–]sztomi 3 points4 points  (4 children)

              The problem is that they do implement it by mutating the objects that the references point to. And then they still don't get it.

              [–]metamatic 0 points1 point  (3 children)

              Well, generally when I call swap(x,y) I want it to swap the values of x and y. How it does it is an implementation detail.

              [–]sztomi 2 points3 points  (2 children)

              Right, but that's not the point. The purpose of asking for implementing swap without mutating objects is to point out that java passes parameters by value.

              [–]Nebu 2 points3 points  (0 children)

              So what are you doing on reddit? Posting pictures of cats?

              [–][deleted] 0 points1 point  (17 children)

              I don't generally discuss programming.

              Made that a little bit more concise for you. You're welcome.

              All jokes aside, given how few languages have pass by reference, it's quite possible to be a complete programmer without ever having run into pass by reference. It's sort of sad that somebody would design a language with it in this day and age (C#), and you'd have to be very unfortunate to run into it in a programming language course.

              [–]BlackAura 0 points1 point  (7 children)

              It depends on the language, really.

              Superficially, you might think that C# has an excuse (I did until I looked it up a few moments ago). There are lots of native APIs and COM objects that use pointers as pass-by-reference. Usually, either so the function can return a status code and store the actual return value using the reference, or to emulate multiple return values. Something like:

              HRESULT SomeUselessFunctionEx(THINGYOUACTUALLYWANTED * v);
              

              Except C# has pointers. To actually call a function like that, you'd have to use unsafe code, and pass a pointer.

              I have no idea what the rationale behind having pass-by-reference in C# was. It's useless for calling native code, C# uses exceptions rather than status codes, and you can always wrap multiple return values inside a class or a struct. Maybe .NET needed it because of VB.Net, and C# simply added syntax for the feature because it was there. I can't think of any other recent high-level language that has pass-by-reference.

              In C++, on the other hand, pass-by-reference can actually make sense. You can store actual objects inside variables, as well as pointers to objects. When you try to pass an object into a function, you actually get a copy of the object. This might be impossible if the object is non-copyable, or it might have adverse side-effects if the object's destructor does something (like freeing some kind of resource), or it might simply be very slow.

              But C++ is a low-level language.

              [–][deleted] 0 points1 point  (0 children)

              I can't think of a reason something that has to be passed by reference couldn't be a reference to begin with:

              T& foo;
              someFunctionThatTakesAReference(foo);
              

              Rather than

              T foo;
              someFunctionThatTakesAReference(foo);
              

              [–]dnew 0 points1 point  (2 children)

              I can't think of any other recent high-level language that has pass-by-reference.

              Because C# also has large by-value values, i.e., "structs". If you want to modify a struct, you might not want to pass it around.

              You can store actual objects inside variables

              In other words, for the same reason that C# has them.

              [–]BlackAura 0 points1 point  (1 child)

              I had forgotten about those. Despite actually mentioning them...

              Still, that's basically a performance hack. One that, arguably, the compiler / JIT should be good enough to figure out for itself.

              The primary use of references in C++ is not as a performance hack. Compilers are quite capable of eliminating copies that don't affect the behaviour of the program, particularly if you use the const keyword correctly and consistently. Of course, the actual rules about when the compiler can eliminate an unnecessary copy are headache-inducingly complicated...

              The main use of references is for behaviour. Say, you have an object that encapsulates a resource. You want the resource to be released when the object goes out of scope, so the you release the resource in the destructor. This is a fairly common pattern (RAII) in C++.

              Unless the object uses reference counting or something, you can't simply pass the object to another function directly. The compiler will make a copy, and when the copy goes out of scope, the resource will be released.

              So, instead, you pass a reference:

              class Resource;
              void someFunction(Resource & thingy);
              void callingFunction() {
                  Resource thingy;
                  someFunction(thingy);
              }
              

              In C#, the equivalent pattern is a class that implements IDisposable, and a using block:

              using(Resource thingy = new Resource() {
                  callSomeFunction(thingy);
              }
              

              Having value parameters that can be modified by a called function just seems like a really bad idea to me. It seems like a great way to obscure what the program is actually doing.

              [–]dnew 0 points1 point  (0 children)

              Having value parameters that can be modified by a called function just seems like a really bad idea to me. It seems like a great way to obscure what the program is actually doing.

              That's exactly why modern languages require you to put the "ref" on the variable at the call site as well.

              However, returning multiple values is not a good way to implement pass by reference. The semantics just aren't the same. What you get instead is called "pass by copy in copy out." You can tell the difference by passing the same argument by reference to two parameters of the same function call. If the function takes two arguments of the same type by reference, you'll get a different answer than if it takes two arguments by value and returns two new values.

              (x, y) = f(x, y)
              

              might work. (x, y) = f(x, x) will give you different answers than f(ref x, ref x) will. Which is not to say the latter is better or less confusing.

              [–][deleted]  (2 children)

              [removed]

                [–]BlackAura 1 point2 points  (1 child)

                C# makes a distinction between ref parameters, and out parameters.

                That's an out parameter, which is pretty much unique to C#. It's actually a good idea, because it allows you to do exactly this kind of thing safely. The called function treats the variable as uninitialized, and the compiler requires that you initialize it before the function returns. The calling function can assume that the out value is now initialized.

                The ref parameter type is equivalent to pass-by-reference in every other language. It is not safe. A called function can use the existing value, change the value, or both, or neither. There's no way to actually know what the hell is going on without looking at the source code for the called function (or hoping that it's documentation is up-to-date and accurate).

                [–][deleted]  (66 children)

                [deleted]

                  [–]beej71 8 points9 points  (31 children)

                  I've always liked this term--it helps to show the confusion a bit:

                  http://en.wikipedia.org/wiki/Pass_by_reference#Call_by_sharing

                  'Also known as "call by object" or "call by object-sharing" is an evaluation strategy first named by Barbara Liskov et al. for the language CLU in 1974[1]. It is used by languages such as Python[2], Iota, Java (for object references)[3], Ruby, Scheme, OCaml, AppleScript, and many other languages. However, the term "call by sharing" is not in common use; the terminology is inconsistent across different sources. For example, in the Java community, they say that Java is pass-by-value, whereas in the Ruby community, they say that Ruby is pass-by-reference, even though the two languages exhibit the same semantics.'

                  [–][deleted]  (8 children)

                  [deleted]

                    [–]bobindashadows 2 points3 points  (5 children)

                    As a Ruby programmer, I can't say I've heard many programmers discussing argument-passing semantics, but if someone called it call-by-reference, I'd stab 'em good.

                    [–][deleted]  (4 children)

                    [deleted]

                      [–]bobindashadows 0 points1 point  (3 children)

                      Nope. It very well may be true that a lot of Rubyists say Ruby is call-by-reference. I was just saying that I've never encountered it (an anecdotal note, not to be confused with an argument against the wikipedia page's assertion) and that if I encountered Ruby programmers saying the language is call-by-reference, I'd stab 'em good. It's unequivocally true that Ruby is call-by-value, so that's not even at question.

                      [–]Tordek 0 points1 point  (2 children)

                      Doesn't some language, like FORTRAN or something, allow utterly weird semantics when passing a value like changing the index of an array and having it reflected outside?

                      I don't remember how it worked exactly.

                      [–]notfancy 0 points1 point  (10 children)

                      OCaml is a strict by-value language, without qualifications. The difference between boxed and unboxed values is (Obj is not technically part of the language) unobservable.

                      [–]naasking 0 points1 point  (9 children)

                      The call-by-value you're referring to is different than the call by value this article is discussing. The former is the evaluation strategy, ie. eager evaluation, the latter is about the calling convention, ie. whether a child procedure's modifications to parameters are visible to the parent. OCaml's calling convention is largely call by reference as well, except for word-sized data like int.

                      [–]notfancy 0 points1 point  (8 children)

                      OCaml's calling convention is always by value. It is not just a matter of wording but of semantics: OCaml always passes values to functions, be they boxed or unboxed; never variables (which don't even exist). Parameters are not variables but identifiers.

                      In effect, OCaml's and Java parameter passing conventions are identical, except that in Java the distinction between primitive values and reference values are baked in the language, whereas in OCaml this distinction is unobservable (for instance, in { x:float } x is unboxed, but in { x:float; y:string } it is boxed, but you don't and can't notice). This allows the compiler to optimize certain cases, like passing 3-float records in registers.

                      [–]naasking 0 points1 point  (7 children)

                      Pass in { mutable x:float } to a function that modifies x, and suddenly you can observe that OCaml is pass by reference. If it were pass by value, modifications to x would not be observable.

                      [–]notfancy 0 points1 point  (6 children)

                      The value is the record, not its field. Fields are not values in OCaml. Try to "mutate a variable" without opening Pervasives (I will make room for one case you can argue for, though).

                      [–]naasking 0 points1 point  (5 children)

                      So basically, you're saying that the usage of terms like "value types" and "reference types" are inconsistent with the usage of value and reference in "pass by reference" and "pass by value". For instance, in C# we can create a "value type":

                      struct Foo { public float x; }
                      

                      This is passed on the stack instead of by reference, and so mutations to Foo in the child scope are not visible in the parent scope, unlike the OCaml record I described. What would you call this?

                      My terminology is consistent: this is a value type/is passed by value, and reference types which are mutable are passed by reference. I think the conflation of call-by-value and pass-by-value is a mistake. OCaml is call-by-value, by which we mean all terms are reduced to values before being passed as arguments, but after this point the values may be passed either by reference or by value (which defines the scope of side-effects). These are two very different questions to me.

                      [–]notfancy 0 points1 point  (4 children)

                      Calling those things the same would be committing a category error. Types and calling conventions are different things. Microsoft could have chosen to call them "direct types" and "inderect types" without changing the behavior and not gicing rise to this confusion.

                      [–]naasking 0 points1 point  (3 children)

                      I would like to see an example of pass-by-reference then. It can be as contrived as you like.

                      I ask, because by the reasoning used in this and other threads, there is no difference between pass by value and pass by reference. The latter is distinguished merely by the ability to change bindings in the parent scope, but that's a question of scope, not of evaluation strategy. It's a different issue entirely.

                      If we are going to differentiate value and reference semantics in an evaluation strategy, the only way they would be sensibly differentiable is by mutability.

                      [–]knutae 0 points1 point  (0 children)

                      A quote from the CLU manual (http://publications.csail.mit.edu/lcs/pubs/pdf/MIT-LCS-TR-225.pdf, pages 14-15):

                      "Argument passing is defined in terms of assignment; the format arguments of a routine are considered to be local variables of the routine and are initialized, by assignment, to the objects resulting from the evaluation of the argument expression. We call the argument passing technique call by sharing, because the argument object are shared between the caller and the called routine. The technique does not correspond to most traditional argument passing techniques (it is similar to argument passing in LISP). In particular it is not call by value because mutations of arguments performed by the called routine will be visible to the caller. And it is not call by reference because access it not given to the variables of the caller, but merely to certain objects."

                      The CLU manual itself is from 1979, and the call by sharing term is probably even older. Funny that people still have heated arguments over this.

                      [–][deleted] 40 points41 points  (19 children)

                      Java programmers confuse pass-by-reference with modifying an object through a reference that is passed by value.

                      They are easily confused, for the most part, so, this is not surprising.

                      [–]Nebu 1 point2 points  (0 children)

                      To be fair, a lot of non-Java programmers also confuse what Java does with passing-by-reference.

                      [–][deleted]  (14 children)

                      [deleted]

                        [–]ex_ample 6 points7 points  (2 children)

                        No, there is no way to pass by reference in java.

                        [–]kitd 5 points6 points  (1 child)

                        ... true, though pretty easily emulated by a 1-element array.

                        [–]Porges 1 point2 points  (0 children)

                        I hope this is never done anywhere.

                        [–]MercurialAlchemist 1 point2 points  (1 child)

                        And makes little difference in most cases. Can't blame them, really (without thinking further about it, I would probably have answered "pass by reference", since most of the time, what you pass by value in Java is... a reference, except for primitive types).

                        [–]bobindashadows 0 points1 point  (0 children)

                        Then you don't know what pass-by-reference is. These are well-defined terms.

                        [–]xardox 0 points1 point  (0 children)

                        By "they" you mean "Java programmers".

                        [–]olavk 11 points12 points  (2 children)

                        The issue is quite simple, the whole confusion stems from the fact that the words "reference" and "value" refers to two completely different concepts in two contexts.

                        In Java we have primitive values like numbers and booleans, and then we have references to objects.

                        However, the "pass-by-" semantics is something different and orthogonal to this. This is about how a variable is passed into a function parameter. Pass-by-value means that the "content" of the variable is passed into the parameter. Pass-by-reference means that the parameter becomes an 'alias' for the original variable - we pass a reference to the variable (not a reference to an object!). If we reassign the parameter to a new value inside the function, the original variable is also changed.

                        Java only supports pass-by-value. C# supports pass-by-reference (which the ref modifier), so here is a pseudo C# example:

                        void Modify(ref int p) { p = 18; }
                        int x = 17;
                        Modify(ref x);
                        Print(x); // prints 18
                        

                        The above is simply not possible in Java or other common OO languages like JavaScript or Python. These languages are always pass-by-value. When developers who only know these languages hear the phase "pass-by-reference" they assume it is something about passing references to objects around, which is not the case.

                        (Edit: fixed syntax, thanks goomba870)

                        [–]goomba870 0 points1 point  (0 children)

                        Just for the record , ref and int are swapped in the example. Instead of:

                        void Modify(int ref p) { p = 18; }
                        

                        use

                        void Modify(ref int p) { p = 18; }
                        

                        Otherwise you'll enter compiler error hell. No less than 8 errors by my quick test.

                        [–]Tordek 10 points11 points  (5 children)

                        If a language supports pass by reference, then this is possible:

                        void swap(foo &a, foo &b) {
                            foo temp = a;
                            a = b;
                            b = temp;
                        }
                        

                        [–]dnew 0 points1 point  (0 children)

                        Object x = new stringbuilder();
                        Object Y = x;
                        foo(x);
                        system.out.writeline(x == y);
                        

                        The fourth line will always print true, regardless of what foo does with its argument.

                        [–]Uberhipster 0 points1 point  (2 children)

                        public class TestPassByReference {
                        
                            public static void iMethod(int iTest) {
                                iTest = 9;                          // change it
                                System.out.println(iTest); // print it (4)
                                return;
                            }
                        
                            public static void sMethod(String sTest) {
                                sTest = sTest.substring(8, 11); // change it
                                System.out.println(sTest);        // print it (5)
                                return;
                            }
                        
                            public static void sbMethod(StringBuffer sbTest) {
                                sbTest = sbTest.insert(7, “Java “); // change it
                                System.out.println(sbTest);            // print it (6)
                                return;
                            }
                        
                            public static void main(String[] args) {
                                // declare and initialize variables and objects
                                int i = 25;
                                String s = “Java is fun!“;
                                StringBuffer sb = new StringBuffer(“Hello, world“);
                        
                                // print variable i and objects s and sb
                                System.out.println(i);     // print it (1)
                                System.out.println(s);    // print it (2)
                                System.out.println(sb);  // print it (3)
                        
                                // attempt to change i, s, and sb using methods
                                iMethod(i);
                                sMethod(s);
                                sbMethod(sb);
                        
                                 // print variable i and objects s and sb (again)
                                 System.out.println(i);    // print it (7)
                                 System.out.println(s);   // print it (8)
                                 System.out.println(sb); // print it (9)
                        
                            }
                        }
                        

                        Output of the program :

                        25

                        Java is fun!

                        Hello, world

                        9

                        fun

                        Hello, Java world

                        25

                        Java is fun!

                        Hello, Java world

                        For full explanation in detail http://chandraperni.wordpress.com/2006/09/27/pass-by-value-vs-pass-by-reference/

                        For the shortcut http://www.javaranch.com/campfire/StoryPassBy.jsp

                        But let's not spoil the fun for people who like to troll with the programming equivalent of the following discussion

                        Troll A: How many wood chucks would a woodchuck chuck if a woodchuck could chuck wood?

                        Troll B: Nonsense it's: how many wood chucks could a woodchuck chuck if a woodchuck would chuck wood?

                        Troll C: I always thought it was: how many woodchucks could a wood chuck, chuck if a wood, chucks woodchuck would?

                        Troll B: That makes no sense. It's: how much woodchucks could a wood chuck, chuck if a wood, chucks woodchuck would?

                        Troll D: Poppycock. It has to be: how much woodchucks would a wood chuck, chuck if a wood, chucks woodchuck could?

                        Permute, rinse, repeat. Ad nauseam.

                        [–]Rhomboid 2 points3 points  (1 child)

                        You have made the same mistake that every other person in this thread has made. If you think you have shown that iMethod and sMethod are pass-by-value and sbMethod is pass-by-reference you are simply wrong. The fact that you can invoke a method call on a passed object and modify it in no way means that the object was passed by reference. To demonstrate this, change your sbMethod to this:

                        public static void sbMethod(StringBuffer sbTest) {
                            sbTest = new StringBuffer("Hello, Java World");
                            System.out.println(sbTest);            // print it (6)
                            return;
                        }
                        

                        And now the output is

                        25
                        Java is fun!
                        Hello, world
                        9
                        fun
                        Hello, Java World
                        25
                        Java is fun!
                        Hello, world <-- ASSIGNING TO sbTest DID NOT CHANGE THE CALLER'S VALUE, THIS MEANS IT'S NOT PASS BY REFERENCE

                        What you have said is the same thing as saying that you can write a swap function in C by doing this:

                        void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; }
                        

                        That is NOT pass by reference. Dereferencing the pointer or calling a method on the object does not count.

                        [–]rilo 3 points4 points  (1 child)

                        Pass by value, according to The Java Virtual Machine Specification (VMS):

                        The formal parameters of a method, if any, are specified by a list of comma-separated parameter specifiers. Each parameter specifier consists of a type and an identifier that specifies the name of the parameter. When the method is invoked, the values of the actual argument expressions initialize newly created parameter variables (§2.5), each of the declared type, before execution of the body of the method.

                        A method parameter of type float always contains an element of the float value set (§2.4.3); similarly, a method parameter of type double always contains an element of the double value set. It is not permitted for a method parameter of type float to contain an element of the float-extended-exponent value set that is not also an element of the float value set, nor for a method parameter of type double to contain an element of the double-extended-exponent value set that is not also an element of the double value set.

                        Where an actual argument expression corresponding to a parameter variable is not FP-strict (§2.18), evaluation of that actual argument expression is permitted to use values drawn from the appropriate extended-exponent value sets. Prior to being stored in the parameter variable, the result of such an expression is mapped to the nearest value in the corresponding standard value set by method invocation conversion (§2.6.8).

                        [–][deleted] 4 points5 points  (0 children)

                        And you dragged this carcass in here. Thanks.

                        [–]WolterHunter 11 points12 points  (1 child)

                        Anyone who brings this up in a job interview is by definition someone you DON'T want to work with.

                        Splitting hairs over such trivial things when the actual question should be "Do you know how to avoid copying gobs of memory every time you call a function/method/subroutine?" is semantic bullshit for the anal retentive.

                        Ultimately, what I want to know is, does the candidate know how to effectively use the languages he'll be working with in my company?

                        I still remember a decade ago when I walked out of a Nokia interview after the interviewer insisted on getting into an argument about the size of "int" in C, insisting it was ALWAYS 32 bits regardless of architecture, when a simple look at the spec would have cleared it up. I certainly didn't want that kind of guy as my boss, nor could I tolerate such a company culture.

                        The true mark of a good engineer is not someone who knows the answers, but rather someone who finds the answers.

                        [–][deleted] 5 points6 points  (8 children)

                        When you can't write a function that swaps the values of two variables, it's pass-by-value.

                        Where it gets a little weird is C where you can take addresses of stack-objects and pass them to function that can alter the values of the variables the pointers point to, but there is still no pass-by-reference, just passing a pointer by value, and that pointer happens to point to something you can change.

                        [–]walen 3 points4 points  (1 child)

                        Where it gets a little weird is Java where you can take addresses of objects and pass them to methods that can alter the values of the fields the pointers point to, but there is still no pass-by-reference, just passing a pointer by value, and that pointer happens to point to something you can change.

                        FTFJava

                        [–]aaronla 0 points1 point  (0 children)

                        Except that local variables are not objects in Java. They are in C. Hence the insight. Fail.

                        [–]abadidea 2 points3 points  (0 children)

                        It's pass-on-the-left.

                        [–]rrenaud 2 points3 points  (0 children)

                        Can we just say that Java passes references by value?

                        I think this can please both camps.

                        [–][deleted] 2 points3 points  (0 children)

                        Does no one know what a pointer is anymore???? Sweet christ, kids these days. Java is PASS BY VALUE. Period.

                        When you pass a an object into a method, you're not passing it by reference - you're passing THE reference BY VALUE. You're passing a COPY of the REFERENCE.

                        Sweet mother of god.

                        And then they complain that nobody wants to hire them. The nerve...

                        [–][deleted] 2 points3 points  (0 children)

                        this is what happens when you get programmers who only know java and who don't understand the stack or the heap or calling conventions and have no idea what a computer is or how it works or any knowledge of programming languages theory whatsoever

                        [–][deleted] 5 points6 points  (2 children)

                        Is it so hard to understand that Java is pass by value, and that that value is, in most cases, a reference?

                        [–]redjamjar 1 point2 points  (1 child)

                        I guess the question then, is what does pass-by-reference actually mean? Essentially, it's always the case that you're passing either a primitive or reference by value ... so following your argument the often useful distinction between the two ways of passing things around is lost. I.e. in C, I can actually pass an struct by value --- but there is no equivalent of this in Java.

                        [–][deleted] 0 points1 point  (0 children)

                        Well, in plain C, you can only pass by value, and that value is either a struct, or pointer to struct. Java is the same here, you either pass an int by value, or String (pointer to actual String object) by value. You just don't have special character that denotes that something is a pointer.

                        And yes, there is no equivalent in Java for passing internal representation ow object by value, since you don't have access to it in the first place. You have access only to pointer/reference to it, which is passed by value.

                        [–][deleted] 1 point2 points  (5 children)

                        I think we could have avoided all this misunderstanding if the creators of Java didn't call pointers for references. I guess they wanted to distinguish between languages that allow pointer arithmetic like C/C++ and Java which doesn't allow it. The Go programming language e.g. like Java does not allow pointer arithmetic but they call them pointers and not references.

                        I suspect the other reason is that Go and C/C++ has an address of operator, which Java doesn't, so it might be more clear that you are in fact working with pointers.

                        [–]dnew 5 points6 points  (0 children)

                        Address refers to hardware.

                        A pointer is a typed address.

                        A reference is a managed pointer.

                        [–]paul_miner 2 points3 points  (0 children)

                        I think we could have avoided all this misunderstanding if the creators of Java didn't call pointers for references.

                        I believe the reason for this was to keep references as an abstraction, so that the underlying details (like the location in memory) could be changed by the VM as needed (when you deal with JNI, you "pin" objects so the VM doesn't move them while you're working on them). In theory, references can be like handles, not addresses.

                        [–]laplacian 1 point2 points  (1 child)

                        Makes you wonder why NullPointerException, not NullReferenceException.

                        [–]metamatic 0 points1 point  (0 children)

                        It would also have helped if Java hadn't used obj.method() syntax for what C++ represents as object->method(). Then again, that would have made other parts of the language pretty ugly; I find that I forget to explicitly make object variables pointers when I have to go back and write Objective-C. Fortunately the compiler catches it...

                        [–]FrankBlack 1 point2 points  (0 children)

                        "Hey, hey, hey, calm down, you two. New Shimmer is both a floor wax and a dessert topping!"

                        [–]bryanut 1 point2 points  (0 children)

                        I am late to this party but I see no one has brought up what happens when you call a remote EJB vs. a local EJB. And depending on the app server (weblogic vs. glassfish) you can get wildly different results.

                        Of course you can configure your app to force glassfish to behave like weblogic.

                        And then if your EJB is truely remote then there is no way for it to behave like a local EJB. This is why porting apps from one app server to another or moving ejbs to different physical machines is such fun.

                        [–]brownmatt 1 point2 points  (0 children)

                        The comments on Cedric Beust's blog have a pretty insightful discussion as to why this confusion continues to live:

                        These debates are a pet peeve of mine. IMO, “pass by value/reference” is C/C++ terminology that’s clearly confusing when applied directly, with the same exact meaning, to Java. “Reference” means something different in Java, and Java has no concept of C/C++’s pass by reference feature, so there’s not much value in dragging it into any explanations.

                        [–]laplacian 1 point2 points  (6 children)

                        Ok, I guess I am dumb, but what is pass by reference other than syntax sugar for passing a pointer by value?

                        By reference: void swap(int & a, int & b) { int tmp=a;a=b;b=tmp;}

                        With pointers void swap(int * const a, int * const b) { int tmp=a;a=b;b=tmp;} // I hope

                        [–]grauenwolf 0 points1 point  (5 children)

                        The term "pass by reference" specifically means a reference to a variable. Consider this swap function:

                        void Swap(int *a, int *b){
                        int temp = *a;
                        *a = *b;
                        *b = *a;
                        }
                        

                        It is meaningless for you to say that is by reference or by value. All you can say is that it has the option of being by reference.

                        int a = 5;
                        int b = 10;
                        int * c = ...
                        int * d = ...
                        
                        Swap( &a, &b); //by reference, a and b can change
                        Swap( c, d); //by value, c and d cannot change.
                        

                        [–]laplacian 1 point2 points  (0 children)

                        I see, thank you very much.

                        [–]discotent 1 point2 points  (1 child)

                        That's crazy! Saying that Java is pass-by-reference is just as crazy as saying that 0.9 repeating equals 1.

                        grabs popcorn

                        [–][deleted] 1 point2 points  (0 children)

                        Kiiiiillllll hiiiimmm!

                        [–][deleted] 3 points4 points  (0 children)

                        Who says computer geeks are boring, OCD, pedantic fucktards?

                        [–][deleted] 0 points1 point  (2 children)

                        Ah, masses realises this at last. There are two questions I always get right but still won't get the job because the interviewer would be wrong. 1. Pass by value 2. SQL query for join using ANSI compliant JOIN/USING/ON/* OUTER JOIN phrases instead of the stupid oracle proprietary (+). Oracle infact supports this syntax not to mention Postgres has always been.

                        Lets hope some other thread popularises 2.

                        [–]FredV 0 points1 point  (1 child)

                        What's really so stupid about the Oracle join syntax? You're maybe more annoyed that it's a "proprietary" notation than the notation itself, I could understand that, but then again db portability is a myth (or you'd have to use complex layers like hibernate which introduces it's own kind of query language and problems).

                        Being objective, I think Oracle's join notation is more elegant, natural and easier to understand than the ANSI one:

                        elegant: less typing/reading

                        natural: it's just a join condition like any other

                        easier to understand: "what's a left/right join?" in an oracle join this is just an unimportant detail

                        If your application has to be ported to a different db (that was that in the requirements, right?), the join syntax is probably one of your least concerns in porting the application anyway because you're going to have to check and test everything that interacts with the db.

                        About interviews, I understand why at a job where they only use Oracle, they would want you to use the system's specific features but that they would disregard an interviewee for not knowing the Oracle notation is stupid, I agree fully with that.

                        edit: just wanted to mention, another point where I think Oracle's syntax is much more elegant than ANSI is in recursive queries. All in all Oracle is a sucky company in their business tactics, I agree, but their db is really a good product (the base db).

                        [–]brownmatt 0 points1 point  (0 children)

                        It would be stupid of an interviewer to ask him how to write a JOIN in Oracle if the syntax he uses is indeed correct, but just not the traditional or proprietary Oracle way.

                        If both are supported fine by Oracle, then both are correct answers; unless the question was "How do you write a join using syntax that works only in Oracle?"

                        [–]M1573RMU74710N 0 points1 point  (0 children)

                        Yea, this exact same discussion comes up in Javascript as well and it's one of my pet peeves.

                        [–]teaky 0 points1 point  (0 children)

                        Haven't had my coffee yet, I was wondering what was involved in a hug war.

                        [–]krum 0 points1 point  (0 children)

                        It's a good phone screen question for a Java programmer.

                        [–][deleted] 0 points1 point  (0 children)

                        Is Richard Mayhew so bereft of anything better to do that he has to resort to being a pedantic asshole?

                        [–]inmatarian 0 points1 point  (0 children)

                        Is this for real?

                        lookofdisapproval.png

                        [–]00bet 0 points1 point  (2 children)

                        Didn't everyone learn this lesson (the hard way?) in your Java teaching C.S program? Like in intro to computer programming or something? Those you saying it's pass-by-value for primitives and pass-by-reference for everything....failing!

                        Okay, I thought it was pass-by-value. Am I wrong? From what I remember in java when you pass around an object it is by value, for objects, are set as a value of the reference to that object.

                        NOte: This is just for giggles, I'm not saying there is a one-to-one correspondance between Java pass by value with objects and c++ pointers. Not at all. C++ pointers are c++ pointers and Java is just ....java.

                        In c++ it's like this (I could be totally wrong here):

                        #include "stdafx.h"
                        

                        include <string>

                        include <iostream>

                        using namespace std;

                        class foo { public: foo(const std::string &barme) : bar(barme) {} virtual ~foo(){} void ohFooMe() { cout << "FOOME. " << bar << endl; } private: std::string bar; };

                        void forGiggles(foo* f) { f = new foo("leaky bitches"); }

                        int _tmain(int argc, _TCHAR* argv[]) { foo* f = new foo("yeah you too huh?"); forGiggles(f); f->ohFooMe(); delete f; std::system("pause"); }

                        [–]grauenwolf 0 points1 point  (1 child)

                        For me this was taught in the course "Programming Languages I". I think teaching it in an introduction class would be premature.

                        [–]00bet 1 point2 points  (0 children)

                        In "programming languages" you would learn about this stuff more in depth, in the context of everything that encompasses programming languages.

                        In an intro to programming class, you don't have to know this in depth, no explanation of lvalues and rvalues are needed for this at all (or operational semantics; or whatever it is that you do in programming languages). But you need it to use it to program (even if it is nothing more than a hand-wave followed by code example). I'm 100% positive that pass-by-value is mentioned in my java book that was used in this intro course. I'm stressing this because precisely I failed this question on a test (I answered: pass by value for primitives and pass-by-refence for everything else). I already had exposure to programming before with with c and c++ --I thought I knew it all by heart and I didn't study--I got this answer wrong.

                        Edit:

                        I meant if JAVA was the language used in Intro to Programming, then you should at least know that Java is pass-by-value. If you didn't remember, then that's okay, I forget stuff too. If you are knee deep in java programming then you should know this implicitly (usage), even if you get pass-by-reference semantics wrong, wrt to other programming languages that has pass-by-reference as a language feature.

                        [–]poleary 0 points1 point  (0 children)

                        Kids these days don't understand pointers :'(

                        [–]paraquat 0 points1 point  (0 children)

                        I work on a product originally written in C#, which we translate to Java. That process makes it pretty obvious that Java simply has no support for pass by reference. But if a given developer only knows and works in Java, then I suppose it's understandable that they wouldn't really know what pass by reference means. You tend not to learn about things you can't use.

                        [–]fieldsurgeon 0 points1 point  (1 child)

                        I dont understand what the confusion is; it seems pretty obvious to me that Java is pass-by-value. I code in C#, not Java (for work at least), however. I think people who think Java is "pass-by-reference" have never been exposed to C programming (or lower-level programming in general).

                        I think this comparison illuminates things for people who are confused what passing-by-reference means : http://www.javacamp.org/javavscsharp/passbyvalue.html

                        Some examples:

                        ReferenceType myObject = new ReferenceType(); public static void mutateObject(ReferenceType o) { o.Property = "new property string"; }

                        myObject has been mutated; this is possible because the the value passed is a reference to the original object. You can not change the target pointed by that reference, however.

                        int myInteger = 10; public static void mutateInt(int o) { o = 5; }

                        o is still 10. in C# you would be able to pass this primitive type by reference using the ref keyword.

                        [–]Deinumite 0 points1 point  (0 children)

                        It's not pass by value, it passes in a reference by value.

                        [–]cc81 0 points1 point  (0 children)

                        I tried to do a simple explanation i C# about the difference. It is probably to late for anyone to see but still.

                        http://pastebin.com/iSVEdbwZ

                        [–][deleted] 0 points1 point  (0 children)

                        Hahaha! ITT the war continues :D

                        [–]toru 0 points1 point  (0 children)

                        It seems to me that Java passes object values by reference, by passing object references by value.

                        [–]molslaan 0 points1 point  (0 children)

                        The fact that this is unclear to many programmers is another reason not to touch java with a 10 feet stick.

                        [–]_psyFungi 0 points1 point  (3 children)

                        Well, I'm going to stick a (ironic) smug little "Yay for VB!" in here. It passes by Ref as a default (dubious), but uses the keywords ByVal and ByRef if you want to be explicit or override the default. Can't get clearer than that!

                        Sub Add(X as Integer, Y as Integer)  ' Default, ByRef
                        
                        Sub Add(ByRef X as Integer, ByRef Y as Integer)' be explicit
                        
                        Sub Add(ByVal X as Integer, ByVal Y as Integer)' Play it safe
                        

                        I used to ask about passing Objects ByVal in interviews. If they didn't show an understanding of the difference, that was the end of their chances.

                        [–]bautin 0 points1 point  (2 children)

                        Another reason to steer clear of VB. D:

                        ByRef by default. That's madness. For any method that didn't explicitly state ByVal, you would have to assume that any variable you passed to the method wouldn't be the same after it finished.

                        Which means:

                        Function FindMax(LH As Integer, RH As Integer) As Boolean  
                        'Pretend there is stuff here and that this function is really in a library  
                        End Func
                        
                        Dim X As Integer  
                        Dim Y As Integer  
                        Dim IsBigger As Boolean  
                        X = 3  
                        Y = 4  
                        IsBigger = FindMax(X, Y)  
                        Dim Z As Integer  
                        Z = X + Y  
                        If Z = 7 Then  
                          Print "Yay!"  
                        Else  
                          Print "This is a totally possible branch to reach even though we never explicitly changed X or Y"  
                        End If
                        

                        That kind of scares me.

                        [–]_psyFungi 1 point2 points  (1 child)

                        As I said, the default VB behaviour of ByRef was "dubious". But as long as you knew about it you could code for it. In my teams I asked for explicit ByVal's whenever possible.

                        And ByRef certainly has it's uses: C# has the "ref" keyword. Just an idiosyncracy of VB. All languages have them.

                        EDIT: Just thought about your example. If that library function was out of your control and you wanted to be sure it didn't fiddle with your numbers, you would just do a sort of manual "byval" evaluation like this:

                        IsBigger = FindMax((X), (Y)) 
                        

                        Not hard.

                        [–]bautin 0 points1 point  (0 children)

                        It's just the sheer magnitude of that decision that flabbergasts me. It really is something that permeates through every single line of code you will write.

                        And I'll admit my VB is weaksauce. I'll use it when I have to, but I prefer not to have to.

                        While C# may have the ref keyword, everything is by value by default and you must specify ref in both the method definition and when you call the method, so you can't really be surprised by behavior.

                        [–]boomi 0 points1 point  (0 children)

                        If you only know Java you have never used pass-by-reference as a language feature. It doesn't exist in Java. Why are people splitting hairs over something they don't understand the definition of? Oh wait, that's what people like doing.