Java is PASS BY VALUE.

Discussions

News: Java is PASS BY VALUE.

  1. Java is PASS BY VALUE. (128 messages)

    So here's the setup: I'm earning my daily bread, and someone tells me, "hey richard, are you watching the linkedin java group thread on pass by value? It's got 240+ messages!" I'm not a member, and my first thought is that I would be afraid to be a member of that group now.

    Look: Java is pass by value.

    If you pass a primitive to a method, you don't get a reference to that primitive; you can't change it in that method. Pass by value.

    If you pass an object reference, including an array, to a method, then the reference value is copied. Pass by value. Since the copied reference value is the same as the reference value that it was copied from, you can modify the state of the referenced object, but you can't alter the original reference in the method.

    Get it right: you can modify the referenced object's state, but you can't modify the reference itself.

    This is not because of magic elfs that defend the reference with life and limb. This is because Java is pass by value.

    If you're one of the people arguing about it NOT being pass by value, then you're wrong. Shut up. Go home. We need to pollinate our gene pool. Too many idiots and not enough lions to eat them.

    Edited by: Bree Nally on Jan 7, 2011 2:30 PM

    Threaded Messages (128)

  2. Punch line which i use[ Go to top ]

    So here's the setup: I'm earning my daily bread, and someone tells me, "hey richard, are you watching the linkedin java group thread on pass by value? It's got 240+ messages!" I'm not a member, and my first thought is that I would be afraid to be a member of that group now.

    Look: Java is pass by value.

    If you pass a primitive to a method, you don't get a reference to that primitive; you can't change it in that method. Pass by value.

    If you pass an object reference, including an array, to a method, then the reference value is copied. Pass by value. Since the copied reference value is the same as the reference value that it was copied from, you can modify the state of the referenced object, but you can't alter the original reference in the method.

    Get it right: you can modify the referenced object's state, but you can't modify the reference itself.

    This is not because of magic elfs that defend the reference with life and limb. This is because Java is pass by value.

    If you're one of the people arguing about it NOT being pass by value, then you're wrong. Shut up. Go home. We need to pollinate our gene pool. Too many idiots and not enough lions to eat them.

    Yes, Java is pass by value for primitives and pass by value for objects too, where the value is the copy of the reference of the object being passed.

  3. Poor Elfs[ Go to top ]

    Everyone disparaging on the magic elfs. They shuttle your values around and when they try to get a break and move a reference around, Java is like "HELL NAW!! YOU MOVE THOSE VALUES AND YOU LIKE IT!! #$%^&!!" And all the Magic Elfs are like... "Okay, Java, okay. Chill out man! See? Values! We're moving them! ...What a prick..."

  4. Java is PASS BY VALUE.[ Go to top ]

    Just a note of caution.  I've wasted many hours trying to get people to understand this.

    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.

    On a side note, a lot of the confusion is really about the difference between pass-by-reference and passing references by value.  To be fair, it's a pretty subtle difference.

     

  5. Java is PASS BY VALUE.[ Go to top ]

    Just a note of caution.  I've wasted many hours trying to get people to understand this.

    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.

    On a side note, a lot of the confusion is really about the difference between pass-by-reference and passing references by value.  To be fair, it's a pretty subtle difference.

    And I thought I was nit-picky :P  I agree there's a subtle difference and I also agree people should understand the difference. I'm not holding my breath though. Any seasoned developer has come across this issue first hand and "should" have taken the time to understand it.

  6. Java is PASS BY VALUE.[ Go to top ]

    Get it right: you can modify the referenced object's state, but you can't modify the reference itself.

    Well what's the difference? Isn't that modifying referenced object's state the same as modifying the reference itself?  If not, what do you mean by modifying a reference?

  7. Java is PASS BY VALUE.[ Go to top ]

    Get it right: you can modify the referenced object's state, but you can't modify the reference itself.

    Well what's the difference? Isn't that modifying referenced object's state the same as modifying the reference itself?  If not, what do you mean by modifying a reference?

    Okay. Let's say we have a reference "a", in a method:

    A a=new A();

    For the sake of argument, let's give the reference (sort of like a C pointer) a value: 1.

    Now we use that reference as an argument to a method, declared as method1(A myA):

    method1(a);

    a gets copied onto the stack. So the method that declares a has a pointer to 1 (called 'a') and method1 has a stack value called myA and scoped locally.

    method1 has this line of code:

    myA.incrementCounter();

    Since it has a copy of the reference (pointing to heap location 1, as above), it can modify the counter by calling the right method through heap location 1. I know I'm describing the terms poorly, but come on, this is pretty common knowledge when it comes down to it - C can do the same thing and in the same way.

    Now, if method1() does this:

    myA=new A();

    What happens? The stack value (which was copied from a) gets changed. So method1() loses track of the original myA, and has a new value to work with. But the only thing that's changed is the value from the stack. The original reference was copied to the stack, but method1 has no actual reference to the original reference.

    Pass. By. Value. You can modify the thing being referenced, but not the reference. The reference you get is a value (a copy) of the original reference.

  8. Java is PASS BY VALUE.[ Go to top ]

    Get it right: you can modify the referenced object's state, but you can't modify the reference itself.

    Well what's the difference? Isn't that modifying referenced object's state the same as modifying the reference itself?  If not, what do you mean by modifying a reference?

    If java were pass by reference, you could make a method like this that would actually accomplish something:

    void swap(Object a, Object b) {

      Object tmp = a;

      a = b;

      b = tmp;

    }

    In a current runtime, the above would like be removed by the jre as it has no net effect.  That is, the caller of the above method can never be affected by it's execution.

  9. Before replying please execute this program.

    package com.test;


    public class SwapTest {
        public static NewString TMP;
        public static void main(String srgs[]){
            NewString a = new SwapTest().new NewString("A-String");
            NewString b = new SwapTest().new NewString("B-String");
            
            System.out.println("Before Swap");
            System.out.println("A :"+a.s1);
            System.out.println("B :"+b.s1);
            
            swapString(a, b);

            System.out.println("After Swap");
            System.out.println("A.S1 - "+a.s1);
            System.out.println("B.S1 - "+b.s1);    
            
        }
        
        public class NewString{
            String s1;
            
            public NewString(){
                s1 = "NewString";
            }
            
            public NewString(String s){
                s1 = s;
            }
        }
        public static void swapString(NewString a, NewString b){
            String s;
            s=b.s1;
            b.s1=a.s1;
            a.s1=s;
            System.out.println("=================================");
            System.out.println("Inside Swap");
            System.out.println("A :"+a.s1);
            System.out.println("B :"+b.s1);
            System.out.println("=================================");
        }
    }

    =============================================================

    As per the concept, reference is the address location of a memory. Whenever a method call happens, JVM will persist the current state. What I could understand from your example is JVM persists the references of the variables passed and re-assigns after method execution. However in my program, swap was done for the values and the change is affected in the Calling program as well.

    Also copy of reference to any seasoned developer means copy of the address location. If the values in the memory location is changed then it is affected in the calling method as well.

    Share your thoughts

  10. I'm not exactly sure what you are trying to prove. That a method can mutate the state of the object being pointed to, as your example demonstrates, has been stated over and over.

    Because Java is call-by-value, the only way to implement the swap function as you implemented it is using wrapper classes. Other often used wrappers are simply arrays or maps.

    If Java was call-by-reference, then the wrapper would not be needed and it would work directly on the type you pass in (e.g. a String).

  11. Java is PASS BY VALUE.[ Go to top ]

    So if I want to tell someone about this great thread should I cut/paste this text into an email or just cut/paste the link.  Is that pass by value or by reference?  I'm so confused.

  12. we interview atleast 50 "senior" java developers before we select one. ( that too out of timeconstraint).

    We get answers like "in a web application  session id is created by browser" :).

    OH! lets not get started on those stupids.

      Its friday.

  13. we interview atleast 50 "senior" java developers before we select one. ( that too out of timeconstraint).

    We get answers like "in a web application  session id is created by browser" :).

    OH! lets not get started on those stupids.

      Its friday.

    man that's hilarious. I haven't come across some one that gave that answer, but I'm sure it's happened.

  14. Java is PASS BY VALUE.[ Go to top ]

    I hate to burst your "I'm so smart and you're all idiots" bubble but the phrase "pass by reference" wasn't intended to indicate the exact mechanism by which values are passed into a function or method.  It was intended to communicate what effect changing those values has on the caller.  The reason the exact mechanism isn't important is that it can vary from language to language and it's not really relevant to the point trying to be communicated.  So, in that sense, Java is very much pass by reference when you're talking about objects.

    As far as I can tell, it's only Java people who think that Java is purely pass by value.  I would suggest actually learning more about the world of software development outside of Javaland before commenting further.  It's really unfortunate that most Java people just don't get it.

  15. Java is PASS BY VALUE.[ Go to top ]

    As far as I can tell, it's only Java people who think that Java is purely pass by value.  I would suggest actually learning more about the world of software development outside of Javaland before commenting further.  It's really unfortunate that most Java people just don't get it.

    I would suggest learning more about computer science before accusing people in Javaland:

    http://en.wikipedia.org/wiki/Pass-by-reference#Call_by_reference

    There is a formal definition of what "Call by Reference" means that has nothing to do with Java. If you've actually done any C++ development, you would clearly understand the difference between pass-by-value and pass-by-reference.

    And yes, if you read further, you will argue that what Java does with object parameters is actually a "call-by-sharing", but that's not an established concept.

  16. Java is PASS BY VALUE.[ Go to top ]

    Perhaps you should read the information at the link you provided more carefully.  Perhaps reading comprehension is at the heart of this problem.

     

    And FYI, I did C for 7 years and C++ for 3.

  17. ... done wrong for 20 years" - I always forget who coined that phrase, but he is right.

    And when you have done C++ for 3 years (real C++ and not "C++ as a better C") you would know better about what Call-By-Reference and Call-By-Value means.

    I always thought that this discussion is purely academic in "Javaland" unless I had to review some production code that was blamed to slow down the whole application. The reason was that the coder did not understand the differences of the concepts and which is used in Java: always Call-By-Value!

  18. production code that was blamed to slow down the whole application. The reason was that the coder did not understand the differences of the concepts and which is used in Java: always Call-By-Value!

    Would you be so kind to share the issue?

  19. Java is PASS BY VALUE.[ Go to top ]

    I hate to burst your "I'm so smart and you're all idiots" bubble but the phrase "pass by reference" wasn't intended to indicate the exact mechanism by which values are passed into a function or method.  It was intended to communicate what effect changing those values has on the caller.  The reason the exact mechanism isn't important is that it can vary from language to language and it's not really relevant to the point trying to be communicated.  So, in that sense, Java is very much pass by reference when you're talking about objects.

    The problem with calling Java pass-by-reference is that it implies something that isn't the case.  What I mean is that I understand your point and your aren't wrong per se but that this fuzzy use of terminology is problematic.  There is a very unambiguous definition of what pass-by-reference means and it's not what java supports.  Overloading this term and making it more ambiguous isn't helping anyone.

    This is an oversimplification but the easiest way (IMO) to understand this is to think of a reference as a value much like an int or a long.  The main difference is that instead of being a numerical value it's a location in a (virtual) memory space.  This location value is passed to methods in the exact same way that an int is i.e. using a copy.

    It because dereferencing is invisible to the developer that it appears that 'an object has been passed by reference'.  In reality, you can't pass objects at all in Java.  You can only pass their (virtual) address.  Again this is all an oversimplification so please don't read too much into it.

  20. Java is PASS BY VALUE.[ Go to top ]

    the phrase "pass by reference" wasn't intended to indicate the exact mechanism by which values are passed into a function or method.  It was intended to communicate what effect changing those values has on the caller.

    On a reread, I noticed this.  This is exactly the point.  In Java, changing the value of a parameter (object or parameter) has no effect on the caller.  That's why stating that Java supports pass-by-reference for objects is incorrect.

  21. Java is PASS BY VALUE.[ Go to top ]

    Yes, I get your point.  I think the problem is that nobody uses the phrase "call-by-sharing" so if you're going to fall back to either call-by-value or call-by-reference, then which is most appropriate?  Unfortunately, neither.  At best, both are misleading.  Consequently I would say that, in this case, arguing it's simply call-by-value is just as bad as saying it's call-by-reference.  Neither term really communicates fully what you're trying to say.

    In any event, as the article in wikipedia states, these terms are not consistently used.

  22. Java is PASS BY VALUE.[ Go to top ]

    It's good to know that in other languages, the exact same semantics are called pass-by-reference.  I was unaware of this.

    The main reason I prefer not to call it that is pragmatic.  I've seen it cause great confusion.  I've read posts where people create elaborate sets of rules to explain observed behavior.  I liken it to the complexity of trying to explain the apparent motion of Mars in an Aristotelian (earth-centered) system.

    Saying Java is pass-by-value always and that references are passed by value may create an initial confusion but is the most straightforward explanation.  It also tends to encourage the confused to gain a deeper understanding.

  23. Java is PASS BY VALUE.[ Go to top ]

    As far as I can tell, it's only Java people who think that Java is purely pass by value. 

    Because the Java Language specification is crystal clear. New variable are created and the values of the parameters copied into them. It's really not up for debate. Even if you have 90 more years of other languages than anyone else.

    http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.1

     

     

  24. I absolutely agree with Marc Stock: what most of us need to know is just the effect changing the values has on the caller.

    We don't need to know about all the internal mechanisms of java, if references are passed by value or values are passed by reference ..  java is not our 'religion' but just something we work with. Times ago i searched the internet to understand if java is pass by value or by reference and found a lot of discussion about the internals of java that was absolutely not useful to me, i just needed to know about the effect changing the values has on the caller.

  25. Why be so anti-intellectual, and insist on being able to use a language without understanding it? Java doesn't have to be your "religion" in order for you to understand how it works. The spec is not like the bible: riddled with contradictions and open to interpretation. It's quite clear on the fact that Java is call by value, not call by reference. 

    Discussions about how Java works may not interest you, and you just want to get your job done, and that's all fine. But that means that you should get another job doing something other than programming Java, if you're not curious enough to learn it well enough to understand something as important as how Java passes parameters. 

    You seem to be confused about the map and the territory, about the object and the pointer to the object. When you say you want to understand the effect of changing "the value", which value do you mean? There's the "value" of the reference or pointer to the object, which is in a parameter variable on the stack. And there's the "value" of the object (the values of its member variables), which is allocated on the heap. 

    This discussion is about the behavior of changing the parameter variable value. Not changing the member variables of the object that the reference points to. That is what pass by value is about. You and Marc seem to be confusing the thing doing the pointing with the thing being pointed to. 

    Even though a pointer refers to another object that's being passed by reference, we can still talk about how the pointer itself is being passed. In Java, that pointer is always passed by value. 

    If you change the value of the parameter variable in the callee, which is a pointer to an object, to point to a different object, then you should understand that the value of the caller's variable will not change, right? The caller's variable will still point to the original object. That is how you know it's pass by value. If you don't understand this, you don't understand Java. 

    The fact that you can dereference the pointer you passed and modify the object it points to is a completely different issue than call by value/reference.

    It's frustrating that so many people are so confused. How many different ways does this need to be explained for people to finally get it? Some people are acting like Tea Party Birthers who have seen Obama's birth certificate (the Java spec) but simply don't believe it. 

    -Don

     

  26. You are right[ Go to top ]

    This discussion is about the behavior of changing the parameter variable value. Not changing the member variables of the object that the reference points to. That is what pass by value is about. You and Marc seem to be confusing the thing doing the pointing with the thing being pointed to.

    I was thinking the same thing. I thought I explained it well, but their replies seemingly make no sense. That is unless they indeed both don't realize what the difference is between the thing doing the pointing with the thing being pointed to.

    To make matters worse, they don't seem to realize they don't realize something. So in their vision their anger is justified. If you honestly don't understand the difference between the thing doing the pointing and the thing being pointed to, then all you see is that you can change the thing being pointed to and "thus" it must be call-by-reference.

    It's like medieval people arguing about how a radioactive stick a few meters away can't possibly hurt them, "since it's not touching them". They may come with theories about how impact of a stick causes bruises and for that to happen physical contact is required, etc etc. But they are totally oblivious about the concept 'radiation', so before they understand that concept they can't possibly understand why the stick is able to hurt being a few meters away.

  27. you misunderstand[ Go to top ]

    Don,

    I said to agree with Mark Stock with one of its statements.

    As regards my point of view, I think you largely misunderstood it.

    I replied to the main thread with a better explanation of what i mean.

  28. Java is call by value, according to the spec, and the computer science definition. 

    If you confuse the pointer with the thing it's pointing at, then you might think that you can modify the thing you're passing, because you're under the mistaken assumption that you're passing the object, not a pointer to the object. 

    Java is different than C++ in that it does not let you put objects into variables. Only pointers to objects. So you can not pass a variable containing an object by value, because you can't have a variable containing an object. Variables can only contain pointers to objects. But when you pass a variable containing a pointer to an object, you always pass the pointer to the object by value. 

    There is no syntax in Java to express a pointer to a pointer to an object, which you would need to "manually" pass a pointer to an object by reference (the way C "manually" implements what C++ calls references, commonly used for "out" parameters). The closest thing you could do would be to put the pointer to an object into another mutable object, and then pass a pointer to that mutable object by value. 

    And really, Marc: 7 years of C and 3 years of C++ is really not a lot of experience, especially in light of the fact that you still misunderstand something as basic as pointers. Condescending arguments from authority don't work when you're making a reference to your own authority, and you're wrong. 

    -Don

  29. ummm... no[ Go to top ]

    @Marc Stock,

         I understand you may view his post as being pretentious in some way, but the fact is that the Java language is in fact pass by value.  A few points:

    1) In order to know that Java is pass by value, you must know Java and programming language concepts.  Therefore, one is not in a position to make judgement UNLESS he or she is a Java person in some way.  I know enough C++ and I know enough Java to be able to tell you the truth.

    2)  Pass by reference and pass by value actually do refer to the exact mechanism by which arguments are passed into parameters.  This has something to do with the programmer's experience, and also how the language is implemented. If you find this difficult to believe, let me prove it to you.  Take a look at this code:

          Car myCar = new Car("Ferrari");

    There are two items here:  A reference variable (myCar) and the actual object it points to (data for a new Ferrari allocated on the heap).  Take a look at the following function:

          doIt(Car theCar){theCar=null;}//Java

    The function will not actually modify the reference.  This is because the reference was copied by value!  How do you do this in C++?

          doIt(Car* theCar){theCar=null;}//C++

    That line of code was the closest analog to Java reference variables in C++.  Java passes *COPIES* of *REFERENCES* ("things *LIKE* pointers").  It does not pass *BY REFERENCE*:

          doIt(Car& theCar){theCar=null;}//C++, the caller now has a nulled pointer...

  30. Please send me teh codez.[ Go to top ]

    I believe there is a strong correlation between those wanting teh codez and those who think java is pass by reference.

  31. Please send me teh codez.[ Go to top ]

    The fact that this NON-TOPIC is the only, uh, topic debated on TSS shows how lame this site has become.

    Even every god damned junior I've worked with knows that it's pass by value.

    WTF?

    TSS: The Stinker Site.

  32. Please send me teh codez.[ Go to top ]

    The fact that this NON-TOPIC is the only, uh, topic debated on TSS shows how lame this site has become.

    Even every god damned junior I've worked with knows that it's pass by value.

    WTF?

    TSS: The Stinker Site.

    Yeah, I think every junior java developer should also know that it's pass by value. But a thread on linkedin, in a group that has people who aren't junior programmers, shows that even "senior developers" don't understand it - and I've seen an email forwarded to me by a someone with that title who argued that it's pass by reference.

    So you can get on your high horse and say "this sucks. this site is lame" all you like, but then again, I haven't seen you submit any news to the front page either - if you submit stuff and it gets rejected, maybe you should talk to the editors to find out why, since you seem to think the bar's so low that you can sneer at the discussions that get discussed.

    Maybe you know it all. that's great. not everyone is as smart as you, i guess. Maybe you'sd like to share your wisdom with the rest of us readers? Or you can shut up.

  33. Please send me teh codez.[ Go to top ]

    The fact that this NON-TOPIC is the only, uh, topic debated on TSS shows how lame this site has become.

    Even every god damned junior I've worked with knows that it's pass by value.

    WTF?

    TSS: The Stinker Site.

    Sure Han, lets go to your favorite site for some "worthy info":

    http://java.dzone.com/articles/value-or-reference

    /Ragnar :-)

     

    :-)

  34. Then you were lucky ...[ Go to top ]

    Even every god damned junior I've worked with knows that it's pass by value.

    Even seniors I had to work with did not even know that there is such a concept and what the differences are - not to speak about the implications coming from there ...

  35. Java is PASS BY VALUE.[ Go to top ]

    It seems to me the problem is one of terminology (and in the case of this thread, a good deal of arrogance). Marc is correct in that the tone of this discussion is not helpful at all. I doubt there is anyone on this forum that knows every nuance and every minute feature of Java, and belittling those who are grappling with the difference between "pass by value" and "pass reference by value" denigrates those hurling the insults more than their targets. As often happens in this field, when a new language is developed, rather than come up with a new term to accurately describe something new, a term is borrowed from existing languages that "almost" describes it. I can just imagine the heated discussions that went on when the Java designers were trying to decide whether to call a method a method (as in Smalltalk) or a member function (as in C++). While I fully understand what happens under the hood when arguments are passed to methods, the term "pass by value" is simply confusing. Pass by value (outside Java) means that a complete copy of the argument is made and passed to the method (as in Pascal). Pass by reference means that only a reference to the object (think C++ pointer) is passed. In Java, neither of these accurately describe what is happening. While it's true that primitives are indeed passed by value in the strict sense of the term, objects are not so clear cut. The truth is that there is a difference between how primitives are passed and how objects are passed. The only semantic difference between how object references are passed in Java and how object references are passed in C++ is that the object reference itself (not the referenced object) is immutable in Java while it is mutable in C++ (unless it's a const - but that's a different story). Calling this "pass by value" is an unnecessary point of confusion to someone who may be versed in other languages. Therefore, my recommendation is, if you are planning on trying to explain this to a novice (or even experienced) Java developer, to tell them that primitives are "passed by value" and objects are "passed by reference value" - oh, and lose the pretentious attitude while your at it.
  36. You're being too reasonable[ Go to top ]

    Mayhew is being a d*ck and just wants to start a fight. He doesn't deserve the attention.

  37. Java is PASS BY VALUE.[ Go to top ]

    Nice article, which has been around for quite some time, http://javadude.com/articles/passbyvalue.htm . Can't belive that someone is still arguing about this.

  38. I think it's not the case with collection.(List,Hashmap etc)

    Here is a sample program i have written and the output, pls. provide your thoughts,

    package misc;

    import java.util.ArrayList;
    import java.util.List;

    public class PassByValue {

        /**
         * @param args
         */
        public static void main(String[] args) {

    //        Java is pass by value for primitives and pass by value
    //        for objects too, where the value is the copy of the reference of the object being passed.
            
            int i = 100;
            
            List<String> l = new ArrayList<String>();
            System.out.println("Primitive Before method -- "+i);
            primitiveTest(i);
            System.out.println("Primitive after method -- "+i);
            
            String x ="hello";
            
            System.out.println("NonPrimitive Before method -- "+x);
            nonPrimitiveTest(x);
            System.out.println("NonPrimitive after method -- "+x);
            
            l.add("one");
            l.add("two");
            System.out.println("List Before method -- "+l.size());
            listTest(l);
            System.out.println("List after method -- "+l.size());
        }
        
        
        static void primitiveTest(int j){
            j = 1001;
        }
        
        static void nonPrimitiveTest(String x){
            x=x.concat("hh");
            System.out.println("NonPrimitive inside method -- "+x);
        }
        
        static void listTest(List<String> l){
            l.add("three");
        }

    }

    ------------------------------------

    Primitive Before method -- 100
    Primitive after method -- 100
    NonPrimitive Before method -- hello
    NonPrimitive inside method -- hellohh
    NonPrimitive after method -- hello
    List Before method -- 2
    List after method -- 3

     

     

  39. Richard explained this as well, If you pass an object reference, including an array, to a method, then the reference value is copied. Pass by value. Since the copied reference value is the same as the reference value that it was copied from, you can modify the state of the referenced object, but you can't alter the original reference in the method.
  40. I got it now,

    I modified the above code a bit,

    static void listTest(List<String> l){
            List<String> z = new ArrayList<String>();
            z.add("Zero");
            l.add("three");
            l = z;
        }

     

    ---------------------------

    List Before method -- 2
    List after method -- 3

    -------------

    In the above method i was trying to modify the reference value to some other ref. value, (by definition of pass by value) it should not have to change. and it didnt change.

     

    so, it's a pass by value, in case of not primitive, the Reference it self sent as a value. (pass by value still).

    Thanks!

     

  41. Java is pass by value . I will try to explain with an example

     

    java code

     

    SomeObect obj1=new SomeObject(1);

    SomeObject obj2=new SomeObject(2);

    swapFunction(obj1,obj2);

    after this function I need the objects to be swapped ie current obj1 represents original obj2 and viceversa.

     

    With java it is not possible.Only thing we can do is we can copy data of obj2 to obj1 and vice versa. but still the hascode or address of obj1 is same as initial obj1

    with c++ it is possible as we are passing references.

    Hope it is ok.

     

     

     

  42. Simple[ Go to top ]

    Java passes references by value.

  43. Simple[ Go to top ]

    Correctly said.! passing references by value!

  44. This is what I explain to junior developers. A) Object exist in memory. In the heap space. B) You always work with reference to them. Multiple reference can reference to same object. C) You pass a copy of the reference (aka it's value) or copy of the primitive (aka it's value) to methods Always works.
  45. microprocessor only knows values[ Go to top ]

    At machine level, only values exist because even memory addresses are copied into registers... you may wonder why other concept exist so, "higher" programming languages provide behaviours and mechanisms for which words/expressions are needed for learning/explanation.

     With EJB method call, it is obvious the call is by value because of the object copy. Then for performance you will find in EJB containers like JBoss or WebSphere a configuration entry named "call by reference" !? The meaning is intuitive: when in same JVM the EJB call does not pass through serialization, no object copy, performance but object from caller may have its internal state modified.

    So are designers from JBoss or IBM wrong or is it simply misunderstanding of conventions ?

     

  46. My opinion is that we cannot say the Java language uses call-by-value semantic because it is wrong for objects. The following assertion is wrong:

    anything passed into a function call is unchanged in the caller's scope when the function returns.

    So Java uses call-by-sharing... except call-by-value for primitive types. Mixed semantic, similar to mixed C++ value/reference.

    As Java language does not give access to object's references themselves (only variables that store internal references, lack of dereference operator), it is difficult to speak about call-by-value with object references.

    For pass-by-reference, you should use java.lang.ref.Reference for all your method parameters and do not use primitive types.

     

  47. It's truly sad that most of you still think it's pass by value. Yes, I fully understand the mechanics of how Java makes a copy of the reference.  As I've already said, and Yves has reiterated, the only term that adequately describes Java's handling is "call-by-sharing" which you can read from the damn wikipedia article if you actually care to learn something.  I repeat, I have absolutely no confusion about how Java handles objects when calling methods.  I totally get it.  Saying over and over that it's "pass by value" does not make it true.  It only makes it true in the mechanical sense but fails to adequately describe the effect.  Call-by-sharing, however, is a much better term.

  48. Could you please have the Java Language Specification changed, it's clearly wrong since it clearly states pass by value.

    Thanks much!

     

  49. RE: Call-by-sharing[ Go to top ]

    It's truly sad that most of you still think it's pass by value. ...  It only makes it true in the mechanical sense but fails to adequately describe the effect.  Call-by-sharing, however, is a much better term.

    Barbara Liskov is a smart woman. And I appreciate her many contributions to the practice and community. However, she coined this term in reference to the language CLU - not Java. The JLS defines the calling semantics as "pass-by-value". You can choose to call it anything you want. We'll call you Humpty Dumpty.

    If I'm interviewing someone for a Java position and ask if Java is pass-by-value or pass-by-reference and they say "pass-by-sharing" I'm marking that answer as wrong. I'd do the same if I asked, "What design pattern do you use when the intent is to be able to attach additional responsibilities to an object dynamically?" I'm expecting them to say "Decorator" because that is the pattern language name we all understand. If instead the interviewee responds "Bedazzler" then they get the question wrong. Period.

  50. Bedazzler Pattern[ Go to top ]

    LOL. Very amusing. You should coin some other pattern synonyms for a Patterns Thesaurus.

    Java is pass-by-value. If you take the SCJP exam, the correct answer is pass-by-value.

    From Richard Raposa, SCJP Exam Study Guide:

    Sun seems to enjoy questions on the exam regarding call by value and methods that attempt to change the value of the argument. If the argument passed into a method parameter is a primitive type, it is impossible in Java for the method to alter the value of the original primitive.

    If the argument passed into a method parameter is a reference type, the same rule applies: it is impossible for a method to alter the original reference. However, because the method now has a reference to the same object that the argument points to, the method can change the object. This is an important difference to understand. Study the upcoming StackDemo program for an example of this situation.

    From 8.4.1 of the Java Language Specification:

    When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared Type, before execution of the body of the method or constructor. The Identifier that appears in the DeclaratorId may be used as a simple name in the body of the method or constructor to refer to the formal parameter.

    I think we all understand both sides of the argument here, but the correct answer is pass-by-value. Cedric B. and Cameron P. agree it is by-value. What more do you need?

     


  51. EJB uses the term differently?[ Go to top ]

    With EJB method call, it is obvious the call is by value because of the object copy. Then for performance you will find in EJB containers like JBoss or WebSphere a configuration entry named "call by reference" !? The meaning is intuitive: when in same JVM the EJB call does not pass through serialization, no object copy, performance but object from caller may have its internal state modified.

    So are designers from JBoss or IBM wrong or is it simply misunderstanding of conventions ?

     

    I noticed the same thing, but the spec actually does clarify it:

     

    Section 3.2.2 Local Clients:

    The arguments and results of the methods of the local business interface are passed “by reference”[1]. Enterprise beans that provide a local client view should therefore be coded to assume that the state of any Java object that is passed as an argument or result is potentially shared by caller and callee.

    [1] More literally, references are passed by value in the JVM: an argument variable of primitive type holds a value of that primitive type; an argument variable of a reference type hold a reference to the object. See [28].

    [28] The Java Virtual Machine Specification.

    (emphasis mine)

    So there you have it, in that particular context "call-by-reference" is used as a shortcut for "references are passed by value". Maybe this is an unfortunate shortcut given all the historical confusion surrounding this, but 'they' thus do actually acknowledge the same thing that most people in this thread are saying. Java is NOT call-by-reference, but passes references by value.

     

     

     

  52. Java is PASS BY VALUE.[ Go to top ]

    This was easier to grasp in assembler code where you could make up the calling conventions for your program or mix them up if you liked to live dangerously.  This was also pretty easy to grasp in C/C++.  If you weren't sure, you could easily single step through the generated assembler code and see the calling convention in action.  If you were coding C on the apple mac, you probably used both calling conventions (since the Mac Toolbox API was call by reference but much of your ported c code probably used call by value convention). 

    In Java, make sure you understand how an object reference is passed in a method call.  If you don't, your code will likely not work in the cases where your understanding is wrong. 

    1.  Primitives are passed by value.  This is obvious.  It would be cool if Java supported marking a parameter as a reference, then a subroutine could modify the original variable passed in.

    2.  Say your writing some code and you new up an Integer and assign it to local variable x.  You will have a local reference to an Integer object (referenced by x).  If you pass x to an object method, the object reference is pushed on the call stack (the value of x).  Again, it would be cool if Java supported marking a parameter as a reference, then the reference to x (think address of x instead of value of x) could be passed.

    Hope this helps

    Scott

  53. Java is pass-by-reference[ Go to top ]

    Java is pass-by-reference like all other programming languages that make use of a garbage collector such as Smalltalk, Lisp, Groovy, Ruby, Scala, etc. The fact that primitives are copied in Java is only a special way Java handles primitives (e.g. Smalltalk, Ruby, Groovy have no primitives - an int is also an instance of a class). That fact that the reference to an object is copied is also only a special way Java does things. Fundamentally, the VM and GC in Java move around references like all other programming systems with a GC whether the are copied to begin with or not.

  54. java is pass by value[ Go to top ]

    C and C++ allow REAL pass by ref.

    So one can change the value of the calling variable on the called method.

    http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr233.htm

     

  55. Java is pass-by-reference?[ Go to top ]

    From what I know, in

    Date a = new Date();

    a is not a Date, but a reference for a Date object.

    This is true for Java as it is true for Groovy and for Scala (I don' t know the other languages good enough).

    A Call-By-Reference would pass the reference to a to the method, but in Java (and Groovy and Scala), the value of a is passed to the method - what implies to my understanding a Call-By-Value.

  56. Java passes Objects BY REFERENCE[ Go to top ]

    To pass an object by value, a copy of the object is made, and the copy is passed to the function.

    C++/C supports this mode by default. JAVA DOES NOT (except for primitives).  Java NEVER makes a copy of the object prior to passing it to the function. Java passes the REFERENCE by VALUE.  It does not pass the OBJECT by value.  HUGE DIFFERENCE!

    Passing by reference allows a swap function to be written that exchanges the contents of the referenced objects.

    In C++, a swap prototype looks like void swap(T &a, T&b). In Java, it is simpler: void swap(T a, T b).  If you argue that I cannot implement the Java swap such that the contents of a and b are swapped, you should not be working in Java.

    Note that even in the C++ case, the addresses of a and b are not swapped.  Similarly, in Java, the Object id's are not swapped.  That is not the purpose of the swap litmus test.

    The initial diatribe of this thread was DEAD WRONG.  

    Mark Hedley

     

     

  57. There is a difference between passing an object by reference, and passing a reference to an object by value. 

    C++ lets you put objects in variables, and those objects by reference. It also lets you put pointers to objects in variables, and pass those by value. 

    Java does not let you put objects into variables. You can only have references to objects in variables, also known as pointers. And Java does not let you pass variables by reference, you can only pass variables by value, by copying them. 

    So Java can't let you pass objects by reference, because its variables can't hold objects, and it can't pass parameters by reference.

    Java does let you pass pointers to objects by value, because its variables can hold pointers to objects (often called "references" and NOT to confused with the term "by reference"), and it can only pass those pointers by value (by copying them, not passing pointers to them). 

    Yes, I argue that you cannot implement the Java swap such that the contents of a and b are swapped. You've written the prototype, "void swap(T a, T b)", now I dare you: write the code, test it, and post it. Does it work? It won't work. It can't work. 

    Have you confused Java with C#, which has "out" parameters that make it easy to write swap?

  58. I absolutely agree with Marc Stock: what most of us need to know is just the effect changing the values has on the caller.

    We don't need to know about all the internal mechanisms of java, if references are passed by value or values are passed by reference ..  java is not our 'religion' but just something we work with. Times ago i searched the internet to understand if java is pass by value or by reference and found a lot of discussion about the internals of java that was absolutely not useful to me, i just needed to know about the effect changing the values has on the caller.

  59. I absolutely agree with Marc Stock: what most of us need to know is just the effect changing the values has on the caller.

    Indeed and this effect is that nothing can assign a new value to a variable the caller has. Whatever happens, after I call foo(bar), I can be sure that bar still points to the same object after the call. The object can be changed, but it can not be pointing to another object.

    Hence Java is call by value, but what you pass around are pointers. What's being pointed to can be changed, but that has very little to nothing to do with the call semantics.

  60. Java is PASS BY VALUE.[ Go to top ]

     

    To be precise, Java is actually pass-by-copy.  Both primitive values and Object references are passed into the method as copies of the originals.

     

  61. Nonsense.[ Go to top ]

    When you qualify "pass by value" with "objects references are passed by value", you are stating that Objects are passed by reference!

     

  62. No nonsense[ Go to top ]

    When you qualify "pass by value" with "objects references are passed by value", you are stating that Objects are passed by reference!

    You pass *a* reference, but you don't pass *by* reference. That's a subtle but important difference.

     

    Can you do it another way in a JVM anyway (you cannot "dereference a pointer" like in C to get its value, everything in Java is referenced AFAIK - excepted primitives) ?


    Good observation Remy, indeed you can't. There's no concept of a "value" or "stack" object in Java like languages as C++ or C# do have. For anyone having a C++ background the difference is rather obvious. Syntax wise Java references may look like C++ stack objects, but they are actually just pointers. In C++ it's immediately clear what's the difference between passing a stack object or passing a pointer and doing any of that either by-value or by-reference (since there's explicit syntax for that).

    So, there are atleast 4 possibilities of passing a parameter:

    Stack object by value (entire object is copied and passed)
    Pointer by value (pointer is copied and passed)
    Stack object by reference ( address of variable holding stack object is passed)
    Pointer by reference ( address of variable holder pointer is passed)

    Each of these has its own behaviour.

    In Java there's only 1 possibilty (pointers being passed by value), so a programmer who has only programmed in Java may not really be aware of or focussed on these differences.

    We all agree here that there are no stack objects in Java (suprizingly, sometimes people even try to argue with that, saying Java doesn't have pointers so it must have only stack objects). This leaves us with only two options left. As I've been saying before, they key difference between pass-by-value and pass-by-reference is that one can change what the original variable holds (not change the thing it points to, but change *what* it points to). You can't do that in Java, so therefore you don't have call-by-reference semantics ;)

    It does not really matter, it's just brain masturbation, but I'd be interested in some official material that details what you say, if you have pointers.


    Well, for starters you might just want to read "the dragon book" (http://www.amazon.com/gp/product/0201100886/104-5987390-6021516?v=glance&;n=283155 ). It has lots of details on the various passing mechanisms (more or less language neutral). I've been reading this when I first started building compilers and it greatly enhanced my insight.

    More specifically I would like to refer to Sierra & Bates in their SCJP book. It has an entire section devoted to exactly this topic:

    I quote:

    Does Java use pass-by-value semantics?

    If java passes objects by passing the reference variable instead, does that mean Java uses pass-by-reference for object? Not exactly, although you'll often hear and read that it does. Java is actually pass-by-value for all variables running within a single VM. [...]
    It makes no difference if you're passing primitive or reference variables, you are always passing a copy of the bits in the variable. [...] if you're passing an object reference variable, you're passing a copy of the bits representing the reference to an object.


    This is near official Sun material as Kathy and Bert are among the people who actually create the SCJP exams. 

    (ps also notice *single VM* being mentioned. When doing RMI, Java can do something like "pass-by-deep-copy" for the special 'remote' objects)

     

     

  63. Richard Mayhew wrote:

    If you're one of the people arguing about it NOT being pass by value, then you're wrong. Shut up. Go home. We need to pollinate our gene pool. Too many idiots and not enough lions to eat them.


    It's a given that someone will make an incorrect statement in public but it's entertaining when they make an incorrect statement and then chastise those who really are on the correct side.


    Java is pass by reference for Objects period.  

    As I explained addressing to the assembly language classes so many years ago, pretend Richard that memory is a bunch of mailboxes; when a Class is instantiated into an Object, the actual Object - a chunk of memory - is inside a mailbox.  The variable that you assigned to this Object when you instantiated it is the _address_ of the mailbox that contains the actual Object.   Other names for this _address_ are 'pointer' and 'reference'.

     
    When you call a method with your Object as a parameter, you are only PASSING a REFERENCE to the actual Object (it makes no difference if the particular language implements this as _copy_ of the reference or not - the fact is that you are passing the mailbox's address and not a copy of what's in the mailbox).  If, as you say, Java passed Objects by value, a whole copy of the Object would have to be made and placed on the method's stack.  This is not the case.


    It is easy to show this to remove all doubt.  If you pass a copy of the Object itself ('pass by value') than the method could not change the original Object, but if you passed a _pointer_ to the object, than the method has access to the original Object and can modify it (assuming it is not immutable like String Objects).
    Copy this piece of code and see for yourself (sorry if it comes out messy - I don't see any 'code' tags):


    public class Test {

        public class Obj1 {

          int a;

           public Obj1() {

            this.a = 1;

          }

          public int getA() {  

             return a;

          }

         public void setA(int val) {

             this.a = val;

          }    

      }    

      public Test() {

        Obj1 o = new Obj1();

        System.out.println("a= " + o.getA());

        changeObj(o, 2);

         System.out.println("a= " + o.getA());

       }  

       public void changeObj(Obj1 o, int val) {

          o.setA(val);    

      }    

      public static void main(String[] args) {

        new Test();

      }

    }

    The original Object is changed by the 'changeObj' method; it couldn't do that if it was only passed a _copy_ of the Object.

    Kevin Ryan

     

  64. Java is pass by reference for Objects period.

    You are wrong period.

    Consider this code:

    Foo foo = new Foo();

    Foo foo2 = foo;

    aMethod(foo);

    assert(foo == foo2); // ALWAYS true

    Your turn...

     

  65. wrong wrong wrong[ Go to top ]

    you need to use equals and compare contents.  you are merely comparing object ids.  the equivalent in C++ would be to use the exact same code you provided and assert (&a==&a2).  was the objective to swap pointers/object-ids or to swap values?  you have certainly not shown that java created a copy of 'a' to pass into the function.

  66. right right right[ Go to top ]

    you need to use equals and compare contents.  

    You are so completely missing the point here. I absolutely did not intend to compare any content, and using the == operator to compare the references themselves was exactly what I intended.

    In C++ I'm able to change what a variable in the calling function point to. Can't do that in Java.

    Java is CALL BY VALUE. Get over it.

  67. nope[ Go to top ]

    C++ truly supports call by value.  A copy of the object is made.  The copy is passed in. Hence, the "value", also known as "content", of the object is passed, not the reference.

    Java does not.  A reference is passed in.  Hence the frequently made statement: "Java passes references to objects by value".  

    Call by value protects the object content from change.  Java does not do this.

     

  68. nope[ Go to top ]

    C++ truly supports call by value.  A copy of the object is made.  The copy is passed in. Hence, the "value", also known as "content", of the object is passed, not the reference.

    Java does not.  A reference is passed in.  Hence the frequently made statement: "Java passes references to objects by value".  

    Call by value protects the object content from change.  Java does not do this.

    You don't get it mate.

    By themselves your statements seem logical, but the error in your reasoning is that C++ has two kinds of variables: automatic / stack / value variables (i.e. Foo) and pointers (i.e. Foo*). Parallel to that, C++ has two calling mechanisms call by value and call by reference (i.e. formal parameter foo and foo&), so all combinations are possible.

    Java doesn't have the automatic / stack / value variable type to begin with. There are only pointers in Java. This initial condition is not understood by people arguing that Java is call by reference. As its stated in logic theory:

    Realize that if the initial statement is false, the resultant conclusion can be false although it is arrived at through a very logical process.

    In Java the only thing you ever pass in are pointers, and the very thing you pass in can't be changed. That the pointer points to something is irrelevant.

    You might as well pass in a primitive integer completely call by value. But suppose this integer happens to be the index to some global array. Of course I can now change the content of said global array cell. According to your logic, the semantics would now change depending on what I do with the primitive integer. Were I to access the array, you would say call-by-refence semantics were in place, but if this very same integer in the very same method was only used to calculate a sum, it would suddenly be call-by-value?

    Sorry, but it just doesn't work like that.

    To add an extra layer of complexity, Java includes native remoting (RMI), and here we see yet another type of calling semantic: a pointer is de-referenced and a *deep* copy is made. Chew on that mate ;)

  69. Can you simply write a C++ code snippet that shows how C++ supports pass-by-reference (which of course it does, I merely stated that C++ supports pass-by-value as well)?  I'd like to contrast it with your code snippet that proves Java does not support pass-by-reference.

     

     

  70. Easy[ Go to top ]

    Can you simply write a C++ code snippet that shows how C++ supports pass-by-reference (which of course it does, I merely stated that C++ supports pass-by-value as well)?  I'd like to contrast it with your code snippet that proves Java does not support pass-by-reference.

    It's the classic swap function that people above gave a couple of times:

    void swap(int& a, int&b) {

        int temp = a;

        a = b;

        b = temp;

    }

    Now suppose we have:

    int a = 1;

    int b = 2;

    swap(a, b);

    cout << a << b << endl; // prints 21

    We have thus changed what a variable in the calling function directly holds. This is impossible in Java.

     

     

     

  71. Easy[ Go to top ]

    No, do it with an object, not a primitive type.  Arbitrary class A.

     

  72. Easy indeed[ Go to top ]

    The example has been given before with objects. It's exactly the same thing. But again for you:
    String a = "hello";
    String b = "world";
    swap(a, b);
    // In Java a points still to "hello"
    // In C++, when using call-by-reference, a points to "world"

    The thing you are confusing is re-assinging a pointer and mutating the state of the object a pointer points to. Those are not the same. Let's take it one step further: String a = "hello";
    String b = "world";
    String c = a;
    swap(a, b);
    In your faulty view, if the method could change "hello" into "world" then after the swap both a and c pointed to this "world". But that is not the idea of call by reference. A would be pointing to "world" and c would still point to "hello".
  73. Easy indeed[ Go to top ]

    All I'm asking for is to see a C++ example, using arbitrary class A.  I want to see how you prove that C++ passes by reference so I can compare your code against the previous Java code which proved that Java cannot pass by reference.

  74. what?!?[ Go to top ]

     

     

    Java doesn't have the automatic / stack / value variable type to begin with. There are only pointers in Java.

    In Java the only thing you ever pass in are pointers, and the very thing you pass in can't be changed. That the pointer points to something is irrelevant.

     

    Well, that just made any further arguments from this 'pass-by-value' character moot.

     

     

     

  75. what, What, WHAT!?[ Go to top ]

     

     

    Java doesn't have the automatic / stack / value variable type to begin with. There are only pointers in Java.

    In Java the only thing you ever pass in are pointers, and the very thing you pass in can't be changed. That the pointer points to something is irrelevant.

     

    Well, that just made any further arguments from this 'pass-by-value' character moot.

    I'm afraid your understanding is so far off, that those two simple facts completely clash with your view of the world. 

    • Java does not have value variables for objects. - This is a basic truth. If you only think of arguing with this, then maybe IT it's just not for you.
    • In Java the only thing you ever pass in are pointers. - This automatically follows from the statement above. If they are no value variables and only pointer variables, you can only pass in pointers.
    • the very thing you pass in can't be changed - This has been demonstrated again and again. If I have a variable String a = "hello"; then a will keep pointing to "hello" no matter what method I pass it into.

    So there you have it, nothing awkward, but for some reason this provoked the reaction "What?" on you. Well, my reaction on that is "what, What, WHAT!?"

     

     

     

  76. Passing "a reference" is different than passing "by reference". The word "reference" is being used in two ways, and you are confusing them. 

    A reference is just another word for a pointer. 

    Pointers are things. Pointers are not objects. Pointers are primitive types. The pointer is not the thing it points to. Get this through your head. Ponder it for a while. Learn it. You will need to understand it, to follow the rest of the discussion. Now that that is out of the way...

    Java variables never contain objects. They always contain pointers to objects (or primitive types). Those pointers are often called "references". But that is a different use of the word "reference" than "call by reference". 

    Those pointers and primitive objects are passed in a certain way. The way they are passed is different from what they are. In Java, the way they are passed is never "by reference". C++ can do that, but Java can't. The way variables are passed is always "by value".

    To recap: "references" are passed "by value" in Java. You never pass objects, because you can't put objects into variables. You can only put "references" to objects in variables, and pass those "by value". 

     

  77. Silly boy[ Go to top ]

    Java is pass by reference for Objects period.

    You are wrong period.

    Consider this code:

    Foo foo = new Foo();

    Foo foo2 = foo;

    aMethod(foo);

    assert(foo == foo2); // ALWAYS true

    Your turn...

    Umm; yeah, that's correct - you just proved my case though.  Your little example creates two references to the same object, of course they are going to equal one another - why would they not?  They are both the address of the mailbox in which the instantiation of Foo resides.

    This isn't rocket science kids.

     

  78. Silly boy[ Go to top ]

     

    Umm; yeah, that's correct - you just proved my case though.  Your little example creates two references to the same object, of course they are going to equal one another - why would they not?  

    It proves that the method is unable to assign a new value to foo. No matter what tricks the method pulls out of its hat, there is no way it can ever let foo point to something else. If Java was call-by-reference, this would have been a simple matter of using the assignment operator in the method to which foo is passed. 

    This isn't rocket science kids.

    Not for kinds, but maybe it is for you?

  79. Sigh. Let's try again.[ Go to top ]

     

    It proves that the method is unable to assign a new value to foo. No matter what tricks the method pulls out of its hat, there is no way it can ever let foo point to something else. 

     

    Good.  So it sounds like you agree that foo is a pointer and not the Object itself.

    When you instantiate a Class into an Object, the variable on the left side of the 'new' is a pointer / reference / address to the Object and not the Object itself.   When you pass that variable as a parameter, you are telling that method where the Object lives in memory so that the method can modify the original Object.  This would not happen if you passed a copy of the actual Object.

    The variable on the left side of the 'new' statement is simply a primitive int or long that represents an address in memory.  Try doing a println on one that doesn't have a toString() method and you will see the actual value.  

    You pass-by-value folks think that because that reference is passed as if it were a primitive (which is indeed correct) that the overall mechanism is pass-by-value.  That is not the case.  The fact is that you passed a reference to the Object so that the method has access to the original Object in memory.

    You could get away with saying that references in Java are passed by value, but you cannot say that Objects are passed by value.   

    Java Objects are passed by Reference.

    That's the way it is - no matter what they taught you in Java-101.

     Kevin

     

     

     

  80. Sigh. Let's try again.[ Go to top ]

     

    Java Objects are passed by Reference.

    Your story is almost correct, up till this point. There is no such thing in Java as a variable that directly represents an Object, so there are no Objects being passed. There are ONLY pointers in Java for non-primitive types.

    Because a Foo pointer in Java is not explicitly expressed as Foo*, it doesn't mean it isn't a pointer. From your previous explanation it seems you understand this.

    The fundamental insight that you seem be missing is that there are thus ONLY pointers (references) in Java and those pointers are passed by value. Or put slightly differently, it's impossible to pass a pointer by reference in Java, simply because Java has no call by reference.

    To re-iterate, Java is call by value.

     

     

     

  81. Sigh. Let's try again.[ Go to top ]

    Mark Stock summed it up nicely in his 14:02 post:

    As far as I can tell, it's only Java people who think that Java is purely pass by value.  I would suggest actually learning more about the world of software development outside of Javaland before commenting further.  It's really unfortunate that most Java people just don't get it.

    As Mark indicates, you really are not seeing the big picture here, and I'm not going to try to explain it to you anymore other than to say that if you told people with experience in this field that Java passes Objects by value, they will have something completely different in mind than you think - with visions of whole Objects being copied onto a method's stack.  And that is not the case.

     

     

     

     

  82. As Mark indicates, you really are not seeing the big picture here, and I'm not going to try to explain it to you anymore other than to say that if you told people with experience in this field

    You mean like people who actually, you know, have build compilers? Or people who have build CPU simulators? Would they be those people "with experience" in your book? I hate to break it to you, but that's actually what I've done. Now I won't call myself the world's compiler expert or anything even remotely close to that, but can you say you have this kind of experience? Even a little?

    that Java passes Objects by value

    Here you go again. Let me spell it out for you:

    Java - does - not - pass - Objects. Period.

    Java passes references (pointers), and those references are passed by value. SIM-PLE.

     

     

     

     

  83. You Got it!![ Go to top ]

     

    Java - does - not - pass - Objects. Period.

    Java passes references

    Finally!

     

     

  84.  

    Java - does - not - pass - Objects. Period.

    Java passes references (pointers), and those references are passed by value.

    Finally!

    Great! Happy to have finally convinced you that there is no call-by-reference in Java, but only references that are passed by value (call-by-value). It takes some courage to change where you stand in a heated discussion, but you did so. My respect!

    Now on to the next heated topic. Care to discuss which web framework is the best one in Java? ;)

     

  85. This is not a matter of opinion.[ Go to top ]

    Mark Stock summed it up nicely in his 14:02 post:

    As far as I can tell, it's only Java people who think that Java is purely pass by value.  I would suggest actually learning more about the world of software development outside of Javaland before commenting further.  It's really unfortunate that most Java people just don't get it.

    As Mark indicates, you really are not seeing the big picture here, and I'm not going to try to explain it to you anymore other than to say that if you told people with experience in this field that Java passes Objects by value, they will have something completely different in mind than you think - with visions of whole Objects being copied onto a method's stack.  And that is not the case.

    I think that just means there are a lot of incompetent developers working in the field who don't understand what "call by value" means, aren't at all interested in knowing, and just want to get their (shoddy) work done. It doesn't mean that the people who disagree with the Java spec have a valid opinion. There are not two valid sides to this argument, and it's not a matter of opinion. 

     

  86. "you cannot say that objects are passed by value". 

    Objects are not passed. References to objects are passed. And those references are passed by value, not reference. 

    If you're saying Java 101 courses and the Java Spec are wrong and you're right, then you're insane. Do you also believe Obama wasn't born in the United States? Really, I want to know. 

     

  87. I asked somebody who knows Java very well:

    Hey I know it's 2011 and we're living in the future and all that, but there still seems to be some confusion and debate about a matter I thought was perfectly clear: Is Java pass by value or pass by reference? 

    and he said:

    Depends on your terminology.  But it's kinda both.  It's pass-by-value for everything, with the twist that for class instances, the thing that's passed-by-value is the pointer to the object, so it behaves like pass-by-reference.

    Reminds me of the controversy about Niklaus Wirth's name:

    "Whereas Europeans generally pronounce his name the right way ('Nick-louse Veert'), Americans invariably mangle it into 'Nickel's Worth.' This is to say that Europeans call him by name, but Americans call him by value." - Introduction by Adriaan van Wijngaarden at the IFIP Congress (1965).

    It looks to me like the confusion seems to be a consequence of pretending pointers don't exist -- you also have to pretend you have variables with object values and references, but you still can't write a swap(a, b) function.

    If you think of Java object values as pointers, then it's obviously passing references by value. But if you don't believe in pointers and think of variables as containing objects, then it's obviously passing objects by reference, but your view of the world is an illusion, because it's really implemented with pointers.

    Or is it??? Someone suggested a Magic Elves theory, which helps a lot of other stuff to make more sense.

     

  88. Java is PASS BY VALUE.[ Go to top ]

    This shouldn't be something to argue about for serious minded Java developers.  That variables are passed by value will feature in one of the first few lessons in Java 101.  Why should this question show up in a forum comprising of developers working on serious real life projects ?

  89. Why this topic is important[ Go to top ]

    I'm really surprised at how many people fail to understand this topic and why it is important. First of all, Java really is PASS BY VALUE. I discovered this when learning Java coming from the C++ world. When you program in C++ you MUST understand the different ways of passing arguments because you have choices in C++ and those choices affect the semantics of your code. Most often you choose between passing an object by value (which can be expensive if the object is large), passing an object by reference, or passing a pointer to the object by value (which is really what Java does, except that Java does it automatically without the pointer operators and Java doesn't allow pointer arithmetic and all those other fancy and dangerous things you can do with pointers).

    So when I started learning Java I discovered that Java had this limitation that it ONLY supported PASS BY VALUE and that it always passes REFERENCES (for objects) or PRIMITIVE VALUES (for primitive types).

    The most obvious example of this limitation in Java (as compared to C++) is when trying to write a swap function, which would be used like this:

      String a = "Hello";
      String b = "World";
      swap(a, b);
      // what is the value of a and b at this point in the code ?

    You can write this function / method in C++ (using pass by reference) but you cannot write it in Java. And you can't cheat here with Java because Strings are immutable. The only way to really swap two Strings in Java is to put them inside an ordered collection (like an ArrayList) and swap their order in the Collection. This works, but the collection (i.e. a reference to the collection) is still passed by value. When you pass a reference by value, you can mutate the object referred to, but you cannot reassign the reference in a way that is visible outside the function.

    But in C++ you can reassign the variable a to "point to" the value "World" and you can similarly reassign the variable b to "point to" the value "Hello" and you can do this inside the "swap" function because the swap function can be written to accept the original references, not copies of the original references.

    I hope this helps. It isn't a knock against Java, but sometimes understanding these things is essential to understanding how to solve problems in the language. And this is important / practical knowledge: I worked on a project in Java where we needed to conditionally swap 2 Strings and we had to use the ArrayList trick, which made for a bit of verbose / ugly code since we had to put the Strings in the ArrayList, call the function containing the conditional swap logic, and then get back the results.

    Mike

  90. Good explanation![ Go to top ]

    +1 for the excellent explanation Micheal gave.

    Shame on those people who now still keep believing Java is somehow call-by-reference. The Java Language Specification clearly states Java is call-by-value and both Micheal and Augustientje explain in detail why this is so.
    Any further statements about Java being call-by-reference are just religious madness and have nothing to do with reality.
  91. No need to be arrogant Richard ![ Go to top ]

    The confusion over this issue is quite understandable given the specifics of Java. The author of this thread is so irritating and comes across as arrogant. Why call people idiots, why not gently explain ?.

    Stop acting like a neanderthal over such a trivial issue. Show some class.

    Java in a Nutshell by David Flanagan puts it best: "Java manipulates objects 'by reference,' but it passes object references to methods 'by value.'"

  92. ...[ Go to top ]

    The fun starts when you get asked this question at an interview. You have to judge the capability of the person interviewing you and decide whether to "dumb down" your answer to "by reference" .... or to tell the truth :-).

     

    This is basic computer science, not java exotica, for the purposes of parameter passing the fact that some VALUES happen to reference objects is irrelevent - they are sill values and passes by copying the value. End of.

    Another clue is contained in the fact that doing 'if(a==b)' compares the reference VALUES not the objects they point to.

     

     

     

  93. A little CS-101 for you c00l-java-d00dz who think, because Java passes references as values, you can infer that it passes Objects by value instead of by reference.

    Here we go.

    If the thing you are passing is copied byte for byte onto the method's stack, you are passing a value.  If instead a pointer to the thing is being passed, you are passing a reference.

    Now here is the important part.  IT DOES NOT MATTER HOW THE REFERENCE IS PASSED - you could email the damn thing - THE FACT OF THE MATTER IS THAT YOU ARE PASSING A REFERENCE instead of a copy of the thing itself.

    There is nothing you can do to change this; passing by reference and passing by value are things in computer science that were around long before you and Java.  Before calling experienced people idiots, perhaps you should broaden your CS skills and gain a little experience yourself.

     

  94. Maybe this will help ...[ Go to top ]

    Noobs argument: 'java is pass by value because the _value_ of the object's reference is passed'.

    Okay let's pass a _pointer_ to the Object's reference (a reference to a reference). 

    Is that then pass-by-reference?  Not by your argument.

    By your argument, the VALUE of the pointer-to-the-reference is what is actually being put on the stack so it is therefore pass-by-value again.  (And you could come up with lame swap methods to prove that it was only the value of the pointer that was passed - which no one disagrees with).

    By your argument there could never be pass-by-reference in ANY language.

     

  95. ... no, it doesn't[ Go to top ]

    Kevin, your problem is not just that you're wrong. Everybody is wrong now and then, no big deal.

    No, your problem is that you are FUNDAMENTALLY wrong!

    All of your explanations are useless, since they all build upon a core principal that you failed to understand. Back trace the steps of your thought process. Forget what you think is true. Learn over. Then you'll see why *you* are wrong and most others here are right. Good luck!

  96. It's dead...[ Go to top ]

    John, I think you killed it.

    http://dilbert.com/strips/comic/2007-12-17/

  97. If the thing you are passing is copied byte for byte onto the method's stack, you are passing a value.  If instead a pointer to the thing is being passed, you are passing a reference.

    Now here is the important part.  IT DOES NOT MATTER HOW THE REFERENCE IS PASSED - you could email the damn thing - THE FACT OF THE MATTER IS THAT YOU ARE PASSING A REFERENCE instead of a copy of the thing itself.

    Sorry, but you really are mistaken.

    I think you are confused between passing a reference and passing by reference. If you pass a reference, the semantics do not automatically become call-by-reference. This is best seen in C++. You have value variables and pointer variables, and both of them can be passed by-value or by-reference.

    So we have:

    1. Value variable passed by-value (this has the major side-effect that a shallow copy of the object is made)
    2. Value variable passed by-reference
    3. Pointer variable passed by-value (this is what Java does)
    4. Pointer variable passed by-reference

    As others have explained, item 1 & 2 are not applicable to Java. Java does not have value variables for classes. Item 4 has been demonstrated to be impossible in Java. You can't write a swap function that swaps what a pointer points to.

    Thus item 3 remains, and this is exactly what Java does: references are passed by-value.

     

     

  98.  

    Thus item 3 remains, and this is exactly what Java does: references are passed by-value.

     

    That is correct, nobody disagrees with it (in fact, see my 'Maybe this will help' post above).  And that reference that is being passed by value is pointing to an Object.

    Where you 'by-value' folks go wrong is then to infer that, because references are passed by value, Java Objects can be said to be pass-by-value.  They are not - Java Objects are passed by reference.  The implementation details of how the reference is passed do not figure into it - like I said, you can email the darn thing.  

    Whether you pass the value of the reference or pass a pointer to the value of the reference does not change the fact that it is a reference to the object being 'communicated' and hence, that object is being passed-by-reference.

    The 'swap' method examples only show that you received the reference as a value and nobody disputes that.  What you need to do is come up with an example that showed that the Object was passed by value and you would not be able to in Java.

    For instance, you would have to write a method that would show when you modified the 'passed' Object, the original Object would not change.  And you cannot do this in Java because the method is handed a pointer to the original Object not a copy of the Object.  When a method is handed a pointer to a thing, in computer science lingo, that thing is referred to as being passed-by-reference.

     

     

     

  99. Where you 'by-value' folks go wrong is then to infer that, because references are passed by value, Java Objects can be said to be pass-by-value.  They are not - Java Objects are passed by reference.

    I would like to advice you to please take John's advice. For the love of God, stop this flawed thought train of yours. Read back Michael Hopper's explanation, and try to understand what he writes. Don't hastily read over it. Really try to understand it. Then read Arjan's post. What are they both saying?

    C++ supports both calling semantics. In C++ too you can pass a pointer to a method. When you do this using call by value, you can still change the object being pointed to. Yet, nobody calls this call by reference, do they? They call this... call by value. 

    Yet you keep arguing that whenever a pointer is involved, then the semantics are always unconditionally call by reference. This is simply not the case. It's a thought that seems to have rooted itself in your head and now you're unable to let it go.

    The call by reference terminology applies to how the variable is passed. It's an extra layer of indirection that gives you a handle to the variable itself, not just to the content or what it points to. A variable is much more akin to a label that is attached to a memory location. This memory location can be the very start of the actual object, or it can be labeling the memory location that contains a memory address where the object can be found.

    In Java the variable always labels the pointer (reference) not the object itself. You thus can't say that objects are passed, since variables in Java never label objects. They always label pointers.

    This is a fundamental insight that you simply don't seem to get.

    Try to repeat the following mantra for yourself:

    In C++ pointers are passed to functions - this can be done via either call by reference or call by value - when pointers are passed it's thus not always call by reference.

    In C++ pointers are passed to functions - this can be done via either call by reference or call by value - when pointers are passed it's thus not always call by reference.

    In C++ pointers are passed to functions - this can be done via either call by reference or call by value - when pointers are passed it's thus not always call by reference.

  100. ...[ Go to top ]

     

    "Thus item 3 remains, and this is exactly what Java does: references are passed by-value."

     

     

     

     

    That is correct, nobody disagrees with it (in fact, see my 'Maybe this will help' post above).  And that reference that is being passed by value is pointing to an Object.

     

    Where you 'by-value' folks go wrong is then to infer that, because references are passed by value, Java Objects can be said to be pass-by-value.  They are not - Java Objects are passed by reference.  

     

    The point is that you are NOT passing an "object". Java doesnt care if an object involved or not. Thats why you can pass a null anywhere where an object REFERENCE is required.

     

     

     

     

  101. The REVELATION!![ Go to top ]

    Haha, you made my day! :D

    This is hilarious. And you know WHAT??

    • The earth is NOT a disc
    • The moon is NOT made from cheese
    • 640k of RAM is NOT enough ;-)

    Cheers
    Luke

  102. Java is a high level programming language. Every programming language has features,set of rules,ect. It can not accept and will not integrate all the peoples needs. It has the feature pass by value.

  103. Again experience vs education[ Go to top ]

    To refer to another thread at LinkedIn Java group, we have again a debate between "educated" guys and "self-made" guys.

    Computer science education tells you what call-by-value/reference means in case of an object oriented language.Theorically Java does not respect either of these two call semantics known before Java exists.

    This thread proves that Java is not an object oriented language as "object are not passed to method", "pointers" and "references" are everywhere... even if the language does not provide any mean to manipulate them. So there is no "object" but only class instance at a memory address where references points to. Do we speak about the language or about the JVM behaviour ?

    By the way Java is a language designed by engineers for engineers and it is really efficient mostly because anyone understands how it work intuitively. But my opinion is that some "shortcuts" has been used in specification/documentation.

     

  104. In concept-oriented programming, pass by-reference and by-value are combined by using concepts which generalize classes. A concept is defined as consisting of two classes: one reference class (passed by-value) and one object class (passed by-reference). For example: 

        concept MyConcept // Used instead of conventional classes
            reference {
                int refField; // Passed by-value
                double refField2;
            }
            object {
                int objField; // Passed by-reference
                MyConcept objField2; // Contains int and double
            }

    So using one construct we can model both methods. In particular, if object class is empty then we get values (with arbitrary structure), and if reference class is empty then we get objects passed by using primitive references.

  105. Spot on. Simple as.[ Go to top ]

    End of discussion

  106. Language lawyers[ Go to top ]

    A trivial c++ example:

    class A {};

    void func(A *);

    void func2(A &);

    int main ()

    {

    A *ap= new A();  //object on heap

    func(ap); //NOT CALL BY REFERENCE, scream the language lawyers!

    A a; // object on stack

    func(&a); //NOT CALL BY REF, scream the lawyers again!

    func2(a); // FINALLY, A CALL BY REFERENCE, scream the lawyers, with their whiny voices!

    }

     

    The java-is-call-by-value language lawyers would have us state that the non-stack-residing object "*ap" is NOT passed by reference to func solely because "ap" is passed by value.  Same with the second invocation of func using &a. 

    How this helps the language lawyers sleep at night is beyond me!

     

  107. The C++ standard[ Go to top ]

    A* ap= new A();  //object on heap

    func(ap); // NOT CALL BY REFERENCE, scream the language lawyers!

    1. You are the one who seems to be screaming, not the supposed "language lawyers"
    2. func is defined as func(A*); It's the actual C++ spec that calls this call-by-value

     

    A a; // object on stack

    func(&a); // NOT CALL BY REF, scream the lawyers again!

    1. Again, you are screaming here.
    2. You're using the address-of operator to obtain a pointer. This pointer is then passed to a function for which we already established it was call-by-value. This example adds little to nothing.
    3. It's the actual C++ spec that calls this call-by-value.

    func2(a); // FINALLY, A CALL BY REFERENCE, scream the lawyers, with their whiny voices!

    1. And again, you are the one who's screaming.
    2. func2 is defined as func2(A &); So yes, according to the C++ standard this is called call-by-reference.

    The java-is-call-by-value language lawyers would have us state that the non-stack-residing object "*ap" is NOT passed by reference to func solely because "ap" is passed by value.

    Indeed, since you'e not passing the dereferenced version of "ap" to func(). The call you're doing is func(ap), so what's getting passed is the pointer "ap", and that pointer is passed by value.

     Same with the second invocation of func using &a. 

    Because it is the same. In this case too you are not passing an object. What you are passing is the address of an object, which is a pointer. Since it's the exact same func, the semantics are the same here. The semantics are tied to the definition of the function, not to where a call-site happens to obtain a pointer from.

    How this helps the language lawyers sleep at night is beyond me!

    Mark, we very much know all of this is beyond you. It's very obvious.

    Do notice that there were only two examples being shown. From the list given by Arjan:

    1. Value variable passed by-reference (func2)
    2. Pointer variable passed by-value (func)

    No definition of func was given, but assume the following:

    void func(A* aPointer) {

       aPointer = new A();

    }

    This assignment will have zero effect on the variable "ap" that's being passed in. If you were to use call-by-reference however this would have an effect.

    This is easily demonstrated with the following code:

    #include <iostream>

     

    class A {

     

       public:

          int value;

     

    };

     

    void callByValuePtrAssign(A* a) {

     

       a = new A;

       a->value = 0;

     

    }

     

    void callByReferencePtrAssign(A* &a) {

     

       a = new A;

       a->value = 0;

     

    }

     

    int main() {

     

       A* a = new A;

       a->value = 3;

     

       cout << "Initial value:" << a->value << endl;

     

       callByValuePtrAssign(a);

     

       cout << "After call by value:" << a->value << endl;

     

       callByReferencePtrAssign(a);

     

       cout << "After call by reference:" << a->value << endl;

     

       return 0;

    }

    The output will be:
    Initial value:3After call by value:3After call by reference:0
    Try for yourself here: http://codepad.org/B0oUJuC8
    In both cases pointers are being passed into the function. In both cases a new instance of A is assigned to the function parameter, and this new instance is mutated to hold the value 0. In the case of the call-by-value version, this change is not propagated to the calling main function. Before and after the call the value is still 3 and thus the a in main still points to the same instance. 
    In the case of the call-by-reference version, the change is propagated, and the value is now 0.
    Now you are probably going to scream that both type of functions can mutate the instance that the A being passed into points to. So, at this point I can imagine your hands itching to write a call-by-value version that also mutates A's value to 0.
    This however is NOT what distinguishes call-by-refernence. Call-by-reference let's the variable being passed in point to another instance, without touching the original. We often don't want to mutate the original A, since others might point to this as well, and they will be effected too.
    This is demonstrated by the following code:
    #include <iostream>
    class A {
       public:      int value;
    };
    void callByValueMutate(A* a) {      a->value = 1;
    }
    void callByReferencePtrAssign(A* &a) {
       a = new A;   a->value = 0;
    }
    int main() {
       A* a = new A;   A* b = a;   a->value = 3;
       cout << "Initial value A:" << a->value << endl;   cout << "Initial value B:" << b->value << endl;
       callByValueMutate(a);
       cout << "After call by value A:" << a->value << endl;   cout << "After call by value B:" << b->value << endl;
       callByReferencePtrAssign(a); 
       cout << "After call by reference A:" << a->value << endl;   cout << "After call by reference B:" << b->value << endl;
             return 0;}
    The output will be:
    Initial value A:3Initial value B:3After call by value A:1After call by value B:1After call by reference A:0After call by reference B:1

    Try this one here: http://codepad.org/Kzxxk6Hp
    What happens is that a new instance is created and both "a" and "b" point to it. If we pass "a" into the call-by-value function, it gets another copy of the pointer pointing to the one and only instance. There are now thus 3 pointers to it. Via this pointer that happens to live in the callByValueMutate function, we mutate the object.
    As expected, after the call we see the change in main via both a en b. This is logical, they point to the same instance. A pointer was involved, the state of an object was mutated, and this change was visible outside the function, but the calling convention is still call-by-value. This is by definition of the C++ spec.
    In the next call we use call-by-reference to pass in "a". Now we assign a new instance to "a" and mutate this. After the call, the change is seen via "a", as it prints the 0 that we assigned to the "value" member of this new instance. However, we haven't touched the instance that a en b originally pointed to. This is seen as we observe that for b the old value is printed.
    It's this last effect that is impossible to achieve in Java. We can mutate the state of the object our pointer points to, but this has the side-effect that everyone else who points to that object also sees this change. If the class involved is immutable (as with a String or a Long) we cannot even do this. What we want to achieve is simply doing an assignment; assign a new pointer. If you want to do this from a function being called, you need call-by-reference. Java doesn't have call-by-reference, so it's impossible to re-assign a variable from the caller in a callee.

  108. Exactly[ Go to top ]

    My point exactly, except I took far fewer words to say it.

    With respect to the OBJECT "*a" in your example, callByValuePtrAssign(a) is a CALL BY REFERENCE.  You get too hung up in seeing that lonely little "a" in your argument list and stopping the thought process at the fact that "a" is passed by value.  

    Here it is for clarity:

    callByValuePtrAssign(a) is a CALL BY REFERENCE with respect to object *a.

    callByValuePtrAssign(a) is a CALL BY VALUE with respect to pointer a;

    Both of these statements are true.  

  109. Exactly[ Go to top ]

    My point exactly, except I took far fewer words to say it.

    With respect to the OBJECT "*a" in your example, callByValuePtrAssign(a) is a CALL BY REFERENCE. 

    Are you insane? I'm not kidding here, but mean this as an honest question. There is no way on earth you can argue with this. The C++ specification clearly states this variant is CALL-BY-VALUE. It's not open for discussion mate. Sorry...

    Go to a C++ forum and try to spread your folly there. Maybe those guys are in for a laugh as well.

    For an extra laugh here, can you give us a Java variant of the C++ call-by-reference function callByReferencePtrAssign()? It's difficult, ain't it?

    void callByReferencePtrAssign(A a) {

       a = new A();

       a.value = 0;

    }

    Now why doesn't this work in Java? Hmmm, would this maybe be because Java has no call-by-reference semantics?

  110. Exactly[ Go to top ]

    Genius can seem like insanity to the lower intellect, but you probably won't understand this.  I'll reiterate this increasingly simple message:

    With Respect To The Object *a, your callByValuePtrAssign(a) is a CALL BY REFERENCE.

    Anybody with a reasonably adequate mind can see that passing a pointer to the object by value is exactly the same concept as passing the object by reference.  I don't care if the function cannot modify the pointer in the calling routine, but if I did, I would have the choice of passing a pointer to the pointer (by value) OR passing the pointer by reference.

     

  111. Exactly[ Go to top ]

    Genius can seem like insanity to the lower intellect, but you probably won't understand this.

    So let me guess, you're the genius and all other people, including those who wrote the Java Language Specification and the C++ standard are the lower intellect?

     I'll reiterate this increasingly simple message:

    With Respect To The Object *a, your callByValuePtrAssign(a) is a CALL BY REFERENCE.

    It just doesn't work like this. This is your own explanation that is true in your own little world, but not in the real world. In the real world *a is irrelevant. **a is also irrelevant and ***a etc are all irrelevant. It's not that what you say here is all by itself completely wrong, but when talking about the calling semantics of a function, the only thing that determines this calling semantic is the definition of the function.

    void func(A*) is CALL-BY-VALUE and void func(A* &) is CALL-BY-REFERENCE.

    Those are really quite simple definitions. It has been said before, in a couple of cases similar effects can be obtained by using either call-by-value or call-by-reference. When I only want to mutate the state of the object being pointed to, passing a pointer by-value or by-reference will both do. When a language has an address-of operator (remember, Java doesn't have this), I can achieve similar effects as call-by-reference with call-by-value. This is all true by itself, but again, none of this changes the definition of what things a method implicitly does. I.e what a method call "automatically" does with respect to the variables being passed in.

    Just try to understand this. When I use call-by-value to pass a pointer and use that to mutate the object this pointer points to, you just can't say that thus call-by-reference has taken place. That you can do a similar thing with call-by-reference just doesn't change the fact that a call-by-value is what has happened.

    Anybody with a reasonably adequate mind can see that passing a pointer to the object by value is exactly the same concept as passing the object by reference.

    You mean like all those people in the C++ forums? Cameron Purdy doesn't have a reasonably adequate mind? Bjarne Stroustrup hasn't seen seen the light yet? Really? And in this topic Michael Hopper, Don Hopkins, Arjan T, Christopher Lord, ... they all just don't understand it, do they?

    Well, just show them all what a genius you are and give us a method in Java then where you can assign a new instance to "a" in the called method, which will be visible in the calling method.

    Is call-by-reference and call-by-value etc is all the same anyway, this should be easy, right?

    I don't care if the function cannot modify the pointer in the calling routine, but if I did, I would have the choice of passing a pointer to the pointer (by value)

    Sure, whatever man, show me the Java code! Prove the world what you're worth!

    String a = "world";

    String b = "world";

    func(a); // Give us the definition of this Mark. Prove Java is call-by-reference!

    assert (a.equals("hello");

    assert (b.equals("world");

    Give us the definition of func that can do this in Java.

  112. Thought I would Chime In[ Go to top ]

    We need to pay attention to the difference between references and pointers, since that seems to be the root of the confusion. These two words don't mean exactly the same thing in different languages. As a compiler developer, I know that these things can be tricky for humans. I've seen more than a few bugs caused by misunderstanding all of this. 

    Pointers are variables that (can) contain the value of an address. You can update that value to be anything though. For example, you can set a pointer to be the digit 15. Or more commonly, you can set it to 0, which many languages including java grant a special name -- null. Also, you can do arithmetic operations on the value contained in a pointer, like p=p+5. Hence, pointers can contain invalid addresses. Java lets you update variables containing addresses (a = new foo(); a = new bar();), and it lets you set them to be invalid addresses like 0 (a = null). Hence, I argue Java Object variables are pointers. The Java compiler (as far as I know) does not permit these pointers to be arithmetically manipulated (a = new foo(); a = a + 5;) but this is a limitation (feature) overlaid on what are, intrinsically, pointers. 

    References are a very special kind of pointer, because the compiler puts very strict rules on them and grants them super-powers when it comes to certain operators. The most important (and most general) difference between references and pointers is that references can not be to arbitrary addresses, like null. They must always refer to an actual object. Moreover, references are fixed and unchanging once initialized, so once they refer to some object, they can never refer to another object. These two properties are fundamental to references in my view, and of course some languages vary in their definition slightly.

    So what good are references, with all of these restrictions and limitations? Good Question! It gets to the heart of the debate. Because references can never be updated, and because they are always valid (i.e., never null or some other garbage,) the compiler can change the meaning of assignment and data reference. Remember how, with pointers, when you assign to them, you change the pointer itself?

    int b = 10;

    int * p = &b;

    p = 5;

    print(p, b); // prints 5, 10

    Now p contains the value 5, which is an invalid address. But no matter, all we've done is updated the value of p. b is unchanged. This is by-value assignment. It is critical to understand this. Now lets look at by-reference assignment, which is similar to by-reference calling conventions:

    int b = 10;

    int &r = b;

    r = 5;

    print(r, b) // prints 5, 5

    Because of the special properties of references, the meaning of the assignment operator is different. Of course, under the covers, both pointers and references are addresses. The words "pointer" and "reference" imply compiler features are at work, like pointer arithmetic and index operators in the pointer case, or modified assignment and guarantees about no nulls in the reference case.

    The above is assign-by-value and assign-by-reference. call-by-value and call-by-reference are very similar:

    int i = 42;

    call_by_reference(i);

    print(i); // prints 6

    call_by_value(&i);

    print(i); // still prints 6, even though we passed a pointer to the function up there

    int * foo = &i;

    pass_pointer_by_reference(foo);

    // now foo is an invalid pointer, because the reference was assigned-to inside the function. i is unchanged still. 

    void call_by_reference(int &r) { r = 6; }

    void call_by_value(int *p) { p = 6; }

    void pass_pointer_by_reference(int *&pr) { pr = 6; }

    So what is java? Well, as mentioned, it seems to implement pointers and a by-value calling/assignment convention. I think it is patently obvious that java is pointer-heavy call-by-value language.  

  113. Thought I would Chime In[ Go to top ]

    So what is java? Well, as mentioned, it seems to implement pointers and a by-value calling/assignment convention. I think it is patently obvious that java is pointer-heavy call-by-value language.  

    Indeed, this is really obvious. I also like the examples you gave. It's hard to believe people still have doubts after reading your explanation. Although it actually is hard to believe that in 2011 people are still discussing this. A decade ago really well written articles had already been written about this topic. Just some references (no pun intended) to some old ones:

    Java Passes References By Value 

    Parameter passing in Java - by reference or by value?

  114. Did you read the references you cite?

    First paragraph of the David Bahr piece. 

     'Recall that in C, C++, and other languages you can choose to pass either a “value” or to “pass a pointer to a value”.  The first option is called “pass-by-value.”  The second option is called “pass-by-reference.” '

    Do you see that?  Can you understand how similar this is to my statement that passing a pointer to a value is called "pass-by-reference"?  Is it clear now?

     

  115. Do you see that?  Can you understand how similar this is to my statement that passing a pointer to a value is called "pass-by-reference"?  Is it clear now?

    -sigh-

    This is in reference to the internal mechanism being used. Why else would the author call the (seemingly) exact same thing call-by-value below:

    On the other hand, Java objects appear to be passed by reference, but it’s a ruse.  All Java objects are pointers (we just don’t have to use the annoying pointer symbol * when we create them), so the pointer gets passed by value (oooh, subtle).

    IF in your deluded world the author says that "passing a pointer to a value explicitly" equals call-by-reference, then why would he say that if you do this it APPEARS to be passed by reference?

    If you pass a VALUE by reference (and remember, Java does not have value variables for objects) then under the hood of course some kind of pointer will be passed. 

    In our beloved C++ again:

    A a; // Watch out if you only know Java, this allocates a complete object in C++

    func(a);

    And func is defined as void func(A &a) { ... } then under the covers some pointer will be passed, in order for the function to be able to access the value residing elsewhere. But this is under the covers. It matters what you as a programmer put into the function and how it comes out on the other side. 

    IT DOES NOT MEAN THE AUTHOR WAS REFERRING TO A METHOD VOID FUNC(A* a);

    This is what you want to be true so badly, that you read in into everything you see. It's really unbelievable. There's an author who clearly explains that Java passes a pointer by-value and does not have call-by-reference, and yet in some twisted way you pick one sentence, ignore the whole conclusion and theme of the article and present that as "proof" that passing a pointer by value is the same as call-by-reference, and thus imply that since this is what Java does, that Java has call-by-reference.

    Can't you see how idiotic that is?

    Can't you really see this???

    The author's entire article is about Java being call-by-value and yet you want to prove with his very own article that java is actually call-by-reference???

    Geesh...

    (p.s. I think we all are still waiting on that very simple piece of code that must be a piece of cake for your brilliant mind to produce. In case you overlooked it, I'll repeat it here:

    String a = "world";

    String b = "world";

    func(a); // Give us the definition of this Mark. Prove Java is call-by-reference!

    assert (a.equals("hello");

    assert (b.equals("world");

    )

     

     

     

  116. Your arguments are crumbling so nicely!

    So let's summarize:

    As stated in one of your references, C++ supports "call by reference" through the passing of a pointer (by value).

    Java does not support anything but references to objects, and therefore cannot claim to pass obects by any means.

    However, in order to be able to talk intelligently about program functionality, one can safely and clearly state that in Java, an object is passed by reference, in the same way that good programmers discuss C++ calling conventions (see your reference above).

    And of course there is no implementation of your java func.  Nobody has suggested even ONCE that Java supports call by reference for anything except objects.  This discussion has been about objects.  Maybe that is what has you so confused.

    Glad I could help clear all of that up!

     

     

  117. Thus Java is call by value[ Go to top ]

    Mark, you lost. You obviously can't write the function requested, since call-by-reference is needed for that.
    Read what Christopher Lord wrote a few posts earlier, and especially read the two articles cited. Don't just read the intro and go dancing with a single sentence like a mad dog.

    Don't they all say Java does not pass objects? Only references are passed, and that happen by value.
    You can write a 1000 follow-up posts, but nothing will ever prove that java is call-by-reference after all. It simply isn't Mark, it simply isn't. Java passes references by value. Nothing more nothing less.

    Now maybe you have better luck arguing at the math4you forum that 1 + 1 really is 3. You'll probably get more supporters for that! Good luck with your quest!
  118. Thus Java is call by value[ Go to top ]

    Not a chance, buddy!  Complete and utter win by the objects-are-passed-by-reference crowd.  When you can write a Java example that creates a copy of the object and passes that object by value, I'll give you your win.  But you can't, cuz Java can't pass objects by value!  It has to pass it by reference using a "pointer" (by value).

    Next, thinkers of your ilk will be claiming that Objects are not supported in any language because the machine code doesn't have the notion of objects.  

     

  119. Thus Java is call by value[ Go to top ]

    When you can write a Java example that creates a copy of the object and passes that object by value, I'll give you your win.  But you can't, cuz Java can't pass objects by value!

    Mark, Java can't pass objects at all...

  120. Thus Java is call by value[ Go to top ]

    Complete and utter win by the objects-are-passed-by-reference crowd.

    p.s.

    What crowd? See this: http://stackoverflow.com/questions/40480/is-java-pass-by-reference

    All the top answers with at the time of writing 142, 90, 30, ...  votes clearly state java is PASS BY VALUE. This is backed by tons of people with quite some reputation (which you don't seem to earn easily there).

    Posting an answer on stackoverflow is free though. I suggest posting your deluded conviction there and let's see how much support you'll get.

    (and let's see in what utterly twisted way you'll this time are going to find 'prove' that java is pass-by-reference from that stackoverflow question where everyone directly and with argumentation states that java is pass-by-value)

     

  121. I've not read every post on this thread admittedly, but I've not seen anyone hit the nail on the head yet.

    Sure, Java is pass-by-value, in the sense that anything that can be passed to a method is passed by value.  But the complication is that you CANNOT PASS AN OBJECT to a method.  You can only pass a reference to an object.  If you could pass an object by value to a method, you would be able to modify its state inside that method without those modifications being visible to the caller.  This is clearly not what happens.  If the only way you can provide a method with access to an object is by passing a reference to that object, then how could you descibe the mechanism by which you are passing that object as anything other than "by reference"?

    Soooo....

    Java is pass by value, but...

    Java cannot pass objects, only object references, so...

    Java effectively passes objects by reference.

    Does that clear it up??? 

  122. Hey, you got it so easily!  Absolutely correct!

  123. Hey, you got it so easily!  Absolutely correct!

    Unfortunately it's still wrong. This too has been mentioned a couple of times in the other threads, but it's always immediately debunked. Read the stackoverflow question for example. One dude proposes this, but he gets several down votes and the person who says he contradicts the other answer gets some 27 up votes.

    There is also not such a thing as Java is pass by value for one kind of thing and pass by reference for another.

    For non-remote calls, Java is exclusively call-by-value. There is no exception. Sorry...

  124. Pass by reference[ Go to top ]

    Ok so with

    #include "stdio.h"

    FILE* fp = fopen("Hello.txt", "r");

    int c = getc(fp);

    I am not using pass-by-reference you say. Sheesh, so much noise for so little.

    Will anyone object if I call Java object parameter passing "Reference passing"?

    http://www.javasyntax.com

  125. Pass by reference[ Go to top ]

    Will anyone object if I call Java object parameter passing "Reference passing"?

    Remeber that Java doesn't pass objects, but references.

    Still maybe nobody will object, but why invent a new term when the existing term pass by value already exists? "Reference passing by-value" might be a better canidate then, as it merely qualifies the existing term. As people indicated above, there are more ways you can think of to call it (call by sharing was mentioned), but unless such a term would get widely accepted it doesn't get you anywhere.

     

  126. Let's clarify some things about my former message. I wanted to highlight the need of a practical description of the topic o fa passing parameters, and that saying 'java is pass-by value' is not enough.

    Actually pretending to solve the problem of passing parameters in java with the simple sentence 'java is pass-by value' can be misleading.

    A good synthesis might be the one in Anthony Jayasekera's message, in which he explains that java is 'pass-by-value' but you need to add you CANNOT PASS AN OBJECT to a method.

    Consider the following simple class

    public class TestClass {

        public static void myMethod(StringBuffer param)
        {        
            param.reverse();
        }

        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            
            StringBuffer local = new StringBuffer("donald");
                    
            TestClass.myMethod(local);                

        }
    }

    Before calling myMethod the 'local' variable value is 'donald'; after calling myMethod the value is 'dlanod'.
    If you just say 'java is pass-by-value' someone clearly could expect the value after calling myMethod is always 'donald'.
    This misunderstanding is due to the fact that the notion of passing parameters by value or by reference was introduced before java and with  respect to languages in which there wasn't a distinction between primitive types and object types.
    Also, the distinction between 'passing by reference', 'passing a reference', and 'passing a reference by value' is a subtle distinction. Actually  'passing by reference' implies 'passing a reference', and 'passing a reference by value' can be considered as just an implementation of 'passing a reference'.

    So my intention was not to contradict that java is pass-by-value or anybody's point of view, i just wanted to explain how the sentence 'java is pass-by-value' can mislead people (and not because they are idiots) and (though at this point personally i might have reached a sufficient knowledge on the topic) the need of practical explanation.


  127. A good synthesis might be the one in Anthony Jayasekera's message, in which he explains that java is 'pass-by-value' but you need to add you CANNOT PASS AN OBJECT to a method.

    Indeed. I think this has been said many times in this thread and in the several articles being cited ;)

    The basic discussion is not about what is easiest to understand, but to what exact scientific definition of the term Java adheres. It has also been said many times that the difference between pass-by-reference and passing a reference by-value is subtle.

  128. Well here you go ... Now you posted your own article, and got your own mega response to it. I thought I finally had peace knowing nobody will mention it again. Well all my previous debacles ... and I decline to say on which side I am ... made be soften up to both sides.

    It is clear that both sides clearly understand the underpinning mechanisms. One side sticks to the definitions in their purest form, the other to the intuitive explanation of what happens. But if one side mention it to the others ... well here we go again.

    To the side with the intuitive approach: think that Java never stores Objects, when it assigns an object, from one variable to another, it passes a reference, not a memory copy. The variables themselves store the references. So if you pass the variable to a method, you pass a reference already. How is it passed? By value! Why I am trying to explain this? Not because you are wrong in what you think, but because I am concerned you wouldn't pass the tests so many times referenced on this thread!

    Now one problem is that the intuitive side would say that they want const parameters, and I would love to see that implemented. But that doesn't help if we stay stuck with it's pure form of the definition. It would be soooooooo useful.

  129. Java compared to C#[ Go to top ]

    Another interesting article that causally mentions Java passes references by value when comparing Java to C#: http://www.harding.edu/fmccown/java_csharp_comparison.html