Is Java “pass-by-reference” or “pass-by-value”?










up vote
5595
down vote

favorite
2564












I always thought Java was pass-by-reference.



However, I've seen a couple of blog posts (for example, this blog) that claim that it isn't.



I don't think I understand the distinction they're making.



What is the explanation?









share















locked by Yvette Colomb Sep 27 at 13:17


This post has been locked while disputes about its content are being resolved. For more info visit meta.











  • 578




    I believe that much of the confusion on this issue has to do with the fact that different people have different definitions of the term "reference". People coming from a C++ background assume that "reference" must mean what it meant in C++, people from a C background assume "reference" must be the same as "pointer" in their language, and so on. Whether it's correct to say that Java passes by reference really depends on what's meant by "reference".
    – Gravity
    Jul 30 '11 at 7:23






  • 100




    I try to consistently use the terminology found at the Evaluation Strategy article. It should be noted that, even though the article points out the terms vary greatly by community, it stresses that the semantics for call-by-value and call-by-reference differ in a very crucial way. (Personally I prefer to use call-by-object-sharing these days over call-by-value[-of-the-reference], as this describes the semantics at a high-level and does not create a conflict with call-by-value, which is the underlying implementation.)
    – user166390
    Dec 15 '11 at 6:12








  • 48




    @Gravity: Can you go and put your comment on a HUGE billboard or something? That's the whole issue in a nutshell. And it shows that this whole thing is semantics. If we don't agree on the base definition of a reference, then we won't agree on the answer to this question :)
    – MadConan
    Nov 12 '13 at 20:58






  • 22




    I think the confusion is "pass by reference" versus "reference semantics". Java is pass-by-value with reference semantics.
    – spraff
    Mar 27 '14 at 13:54






  • 9




    @Gravity, while you're absolutely correct in that folks coming from C++ will instinctively have a different intuition set regarding the term "reference", I personally believe the body is more buried in the "by". "Pass by" is confusing in that it is absolutely distinct from "Passing a" in Java. In C++, however it colloquially is not. In C++ you can say "passing a reference", and it's understood that it will pass the swap(x,y) test.
    – user4229245
    Mar 23 '15 at 13:44

















up vote
5595
down vote

favorite
2564












I always thought Java was pass-by-reference.



However, I've seen a couple of blog posts (for example, this blog) that claim that it isn't.



I don't think I understand the distinction they're making.



What is the explanation?









share















locked by Yvette Colomb Sep 27 at 13:17


This post has been locked while disputes about its content are being resolved. For more info visit meta.











  • 578




    I believe that much of the confusion on this issue has to do with the fact that different people have different definitions of the term "reference". People coming from a C++ background assume that "reference" must mean what it meant in C++, people from a C background assume "reference" must be the same as "pointer" in their language, and so on. Whether it's correct to say that Java passes by reference really depends on what's meant by "reference".
    – Gravity
    Jul 30 '11 at 7:23






  • 100




    I try to consistently use the terminology found at the Evaluation Strategy article. It should be noted that, even though the article points out the terms vary greatly by community, it stresses that the semantics for call-by-value and call-by-reference differ in a very crucial way. (Personally I prefer to use call-by-object-sharing these days over call-by-value[-of-the-reference], as this describes the semantics at a high-level and does not create a conflict with call-by-value, which is the underlying implementation.)
    – user166390
    Dec 15 '11 at 6:12








  • 48




    @Gravity: Can you go and put your comment on a HUGE billboard or something? That's the whole issue in a nutshell. And it shows that this whole thing is semantics. If we don't agree on the base definition of a reference, then we won't agree on the answer to this question :)
    – MadConan
    Nov 12 '13 at 20:58






  • 22




    I think the confusion is "pass by reference" versus "reference semantics". Java is pass-by-value with reference semantics.
    – spraff
    Mar 27 '14 at 13:54






  • 9




    @Gravity, while you're absolutely correct in that folks coming from C++ will instinctively have a different intuition set regarding the term "reference", I personally believe the body is more buried in the "by". "Pass by" is confusing in that it is absolutely distinct from "Passing a" in Java. In C++, however it colloquially is not. In C++ you can say "passing a reference", and it's understood that it will pass the swap(x,y) test.
    – user4229245
    Mar 23 '15 at 13:44















up vote
5595
down vote

favorite
2564









up vote
5595
down vote

favorite
2564






2564





I always thought Java was pass-by-reference.



However, I've seen a couple of blog posts (for example, this blog) that claim that it isn't.



I don't think I understand the distinction they're making.



What is the explanation?









share















I always thought Java was pass-by-reference.



However, I've seen a couple of blog posts (for example, this blog) that claim that it isn't.



I don't think I understand the distinction they're making.



What is the explanation?







java methods parameter-passing pass-by-reference pass-by-value





share














share












share



share








edited Jul 11 at 11:31


























community wiki





21 revs, 17 users 15%
user4315





locked by Yvette Colomb Sep 27 at 13:17


This post has been locked while disputes about its content are being resolved. For more info visit meta.






locked by Yvette Colomb Sep 27 at 13:17


This post has been locked while disputes about its content are being resolved. For more info visit meta.










  • 578




    I believe that much of the confusion on this issue has to do with the fact that different people have different definitions of the term "reference". People coming from a C++ background assume that "reference" must mean what it meant in C++, people from a C background assume "reference" must be the same as "pointer" in their language, and so on. Whether it's correct to say that Java passes by reference really depends on what's meant by "reference".
    – Gravity
    Jul 30 '11 at 7:23






  • 100




    I try to consistently use the terminology found at the Evaluation Strategy article. It should be noted that, even though the article points out the terms vary greatly by community, it stresses that the semantics for call-by-value and call-by-reference differ in a very crucial way. (Personally I prefer to use call-by-object-sharing these days over call-by-value[-of-the-reference], as this describes the semantics at a high-level and does not create a conflict with call-by-value, which is the underlying implementation.)
    – user166390
    Dec 15 '11 at 6:12








  • 48




    @Gravity: Can you go and put your comment on a HUGE billboard or something? That's the whole issue in a nutshell. And it shows that this whole thing is semantics. If we don't agree on the base definition of a reference, then we won't agree on the answer to this question :)
    – MadConan
    Nov 12 '13 at 20:58






  • 22




    I think the confusion is "pass by reference" versus "reference semantics". Java is pass-by-value with reference semantics.
    – spraff
    Mar 27 '14 at 13:54






  • 9




    @Gravity, while you're absolutely correct in that folks coming from C++ will instinctively have a different intuition set regarding the term "reference", I personally believe the body is more buried in the "by". "Pass by" is confusing in that it is absolutely distinct from "Passing a" in Java. In C++, however it colloquially is not. In C++ you can say "passing a reference", and it's understood that it will pass the swap(x,y) test.
    – user4229245
    Mar 23 '15 at 13:44
















  • 578




    I believe that much of the confusion on this issue has to do with the fact that different people have different definitions of the term "reference". People coming from a C++ background assume that "reference" must mean what it meant in C++, people from a C background assume "reference" must be the same as "pointer" in their language, and so on. Whether it's correct to say that Java passes by reference really depends on what's meant by "reference".
    – Gravity
    Jul 30 '11 at 7:23






  • 100




    I try to consistently use the terminology found at the Evaluation Strategy article. It should be noted that, even though the article points out the terms vary greatly by community, it stresses that the semantics for call-by-value and call-by-reference differ in a very crucial way. (Personally I prefer to use call-by-object-sharing these days over call-by-value[-of-the-reference], as this describes the semantics at a high-level and does not create a conflict with call-by-value, which is the underlying implementation.)
    – user166390
    Dec 15 '11 at 6:12








  • 48




    @Gravity: Can you go and put your comment on a HUGE billboard or something? That's the whole issue in a nutshell. And it shows that this whole thing is semantics. If we don't agree on the base definition of a reference, then we won't agree on the answer to this question :)
    – MadConan
    Nov 12 '13 at 20:58






  • 22




    I think the confusion is "pass by reference" versus "reference semantics". Java is pass-by-value with reference semantics.
    – spraff
    Mar 27 '14 at 13:54






  • 9




    @Gravity, while you're absolutely correct in that folks coming from C++ will instinctively have a different intuition set regarding the term "reference", I personally believe the body is more buried in the "by". "Pass by" is confusing in that it is absolutely distinct from "Passing a" in Java. In C++, however it colloquially is not. In C++ you can say "passing a reference", and it's understood that it will pass the swap(x,y) test.
    – user4229245
    Mar 23 '15 at 13:44










578




578




I believe that much of the confusion on this issue has to do with the fact that different people have different definitions of the term "reference". People coming from a C++ background assume that "reference" must mean what it meant in C++, people from a C background assume "reference" must be the same as "pointer" in their language, and so on. Whether it's correct to say that Java passes by reference really depends on what's meant by "reference".
– Gravity
Jul 30 '11 at 7:23




I believe that much of the confusion on this issue has to do with the fact that different people have different definitions of the term "reference". People coming from a C++ background assume that "reference" must mean what it meant in C++, people from a C background assume "reference" must be the same as "pointer" in their language, and so on. Whether it's correct to say that Java passes by reference really depends on what's meant by "reference".
– Gravity
Jul 30 '11 at 7:23




100




100




I try to consistently use the terminology found at the Evaluation Strategy article. It should be noted that, even though the article points out the terms vary greatly by community, it stresses that the semantics for call-by-value and call-by-reference differ in a very crucial way. (Personally I prefer to use call-by-object-sharing these days over call-by-value[-of-the-reference], as this describes the semantics at a high-level and does not create a conflict with call-by-value, which is the underlying implementation.)
– user166390
Dec 15 '11 at 6:12






I try to consistently use the terminology found at the Evaluation Strategy article. It should be noted that, even though the article points out the terms vary greatly by community, it stresses that the semantics for call-by-value and call-by-reference differ in a very crucial way. (Personally I prefer to use call-by-object-sharing these days over call-by-value[-of-the-reference], as this describes the semantics at a high-level and does not create a conflict with call-by-value, which is the underlying implementation.)
– user166390
Dec 15 '11 at 6:12






48




48




@Gravity: Can you go and put your comment on a HUGE billboard or something? That's the whole issue in a nutshell. And it shows that this whole thing is semantics. If we don't agree on the base definition of a reference, then we won't agree on the answer to this question :)
– MadConan
Nov 12 '13 at 20:58




@Gravity: Can you go and put your comment on a HUGE billboard or something? That's the whole issue in a nutshell. And it shows that this whole thing is semantics. If we don't agree on the base definition of a reference, then we won't agree on the answer to this question :)
– MadConan
Nov 12 '13 at 20:58




22




22




I think the confusion is "pass by reference" versus "reference semantics". Java is pass-by-value with reference semantics.
– spraff
Mar 27 '14 at 13:54




I think the confusion is "pass by reference" versus "reference semantics". Java is pass-by-value with reference semantics.
– spraff
Mar 27 '14 at 13:54




9




9




@Gravity, while you're absolutely correct in that folks coming from C++ will instinctively have a different intuition set regarding the term "reference", I personally believe the body is more buried in the "by". "Pass by" is confusing in that it is absolutely distinct from "Passing a" in Java. In C++, however it colloquially is not. In C++ you can say "passing a reference", and it's understood that it will pass the swap(x,y) test.
– user4229245
Mar 23 '15 at 13:44






@Gravity, while you're absolutely correct in that folks coming from C++ will instinctively have a different intuition set regarding the term "reference", I personally believe the body is more buried in the "by". "Pass by" is confusing in that it is absolutely distinct from "Passing a" in Java. In C++, however it colloquially is not. In C++ you can say "passing a reference", and it's understood that it will pass the swap(x,y) test.
– user4229245
Mar 23 '15 at 13:44














77 Answers
77






active

oldest

votes













1 2
3
next











up vote
4906
down vote



+50










Java is always pass-by-value. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners.



It goes like this:



public static void main(String args) {
Dog aDog = new Dog("Max");
// we pass the object to foo
foo(aDog);
// aDog variable is still pointing to the "Max" dog when foo(...) returns
aDog.getName().equals("Max"); // true
aDog.getName().equals("Fifi"); // false
}

public static void foo(Dog d) {
d.getName().equals("Max"); // true
// change d inside of foo() to point to a new Dog instance "Fifi"
d = new Dog("Fifi");
d.getName().equals("Fifi"); // true
}


In the example above aDog.getName() will still return "Max". The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.



Likewise:



public static void main(String args) {
Dog aDog = new Dog("Max");
foo(aDog);
// when foo(...) returns, the name of the dog has been changed to "Fifi"
aDog.getName().equals("Fifi"); // true
}

public static void foo(Dog d) {
d.getName().equals("Max"); // true
// this changes the name of d to be "Fifi"
d.setName("Fifi");
}


In the above example, Fifi is the dog's name after call to foo(aDog) because the object's name was set inside of foo(...). Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog itself (except when d is changed to point to a different Dog instance like d = new Dog("Boxer")).





share



















  • 219




    Isn't it slightly confusing the issue with internal details? There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'.
    – izb
    Sep 8 '08 at 14:58






  • 336




    But there is a subtle difference. Look at the first example. If it was purely pass by reference, aDog.name would be "Fifi". It isn't - the reference you are getting is a value reference that if overwritten will be restored when exiting the function.
    – erlando
    Sep 11 '08 at 6:55






  • 264




    @Lorenzo: No, in Java everything is passed by value. Primitives are passed by value, and object references are passed by value. The objects themselves are never passed to a method, but the objects are always in the heap and only a reference to the object is passed to the method.
    – Esko Luontola
    Feb 12 '09 at 23:02






  • 258




    My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed.
    – dhackner
    Oct 20 '10 at 16:38








  • 126




    What's confusing is that object references are actually pointers. In the beginning SUN called them pointers. Then marketing informed that "pointer" was a bad word. But you still see the "correct" nomenclature in NullPointerException.
    – Prof. Falken
    Feb 9 '11 at 9:46




















up vote
2704
down vote













I just noticed you referenced my article.



The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.



The key to understanding this is that something like



Dog myDog;


is not a Dog; it's actually a pointer to a Dog.



What that means, is when you have



Dog myDog = new Dog("Rover");
foo(myDog);


you're essentially passing the address of the created Dog object to the foo method.



(I say essentially because Java pointers aren't direct addresses, but it's easiest to think of them that way)



Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.



if the Method were defined as



public void foo(Dog someDog) {
someDog.setName("Max"); // AAA
someDog = new Dog("Fifi"); // BBB
someDog.setName("Rowlf"); // CCC
}


let's look at what's happening.




  • the parameter someDog is set to the value 42

  • at line "AAA"



    • someDog is followed to the Dog it points to (the Dog object at address 42)

    • that Dog (the one at address 42) is asked to change his name to Max



  • at line "BBB"


    • a new Dog is created. Let's say he's at address 74

    • we assign the parameter someDog to 74



  • at line "CCC"


    • someDog is followed to the Dog it points to (the Dog object at address 74)

    • that Dog (the one at address 74) is asked to change his name to Rowlf



  • then, we return


Now let's think about what happens outside the method:



Did myDog change?



There's the key.



Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog (but note that because of line "AAA", its name is now "Max" - still the same Dog; myDog's value has not changed.)



It's perfectly valid to follow an address and change what's at the end of it; that does not change the variable, however.



Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, you cannot change where that pointer points.



In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.



If Java had pass-by-reference semantics, the foo method we defined above would have changed where myDog was pointing when it assigned someDog on line BBB.



Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.





share



















  • 120




    This is why the common refrain "Java doesn't have pointers" is so misleading.
    – Beska
    Apr 2 '09 at 17:52






  • 122




    You are wrong, imho. "Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog." myDog has value 42 but its name argument now contains "Max", rather than "Rover" on // AAA line.
    – Özgür
    Apr 6 '09 at 5:22






  • 167




    Think about it this way. Someone has the address of Ann Arbor, MI (my hometown, GO BLUE!) on a slip of paper called "annArborLocation". You copy it down on a piece of paper called "myDestination". You can drive to "myDestination" and plant a tree. You may have changed something about the city at that location, but it doesn't change the LAT/LON that was written on either paper. You can change the LAT/LON on "myDestination" but it doesn't change "annArborLocation". Does that help?
    – Scott Stanchfield
    Apr 23 '09 at 13:06






  • 34




    @Scott Stanchfield: I read your article about a year ago and it really helped clear things up for me. Thanks! May I humbly suggest a little addition: you should mention that there is actually a specific term that describes this form of "call by value where the value is a reference" that was invented by Barbara Liskov for describing the evaluation strategy of her CLU language in 1974, in order to avoid confusion such as the one your article addresses: call by sharing (sometimes called call by object-sharing or simply call by object), which pretty much perfectly describes the semantics.
    – Jörg W Mittag
    Sep 7 '10 at 22:12






  • 23




    @Gevorg - The C/C++ languages don't own the concept of a "pointer". There are other languages that use pointers but do not allow the same types of manipulation of pointers that C/C++ allow. Java has pointers; they're just protected against mischief.
    – Scott Stanchfield
    Dec 30 '11 at 18:30


















up vote
1429
down vote













Java always passes arguments by value NOT by reference.





Let me explain this through an example:



public class Main{
public static void main(String args){
Foo f = new Foo("f");
changeReference(f); // It won't change the reference!
modifyReference(f); // It will modify the object that the reference variable "f" refers to!
}
public static void changeReference(Foo a){
Foo b = new Foo("b");
a = b;
}
public static void modifyReference(Foo c){
c.setAttribute("c");
}
}


I will explain this in steps:





  1. Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".



    Foo f = new Foo("f");


    enter image description here




  2. From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.



    public static void changeReference(Foo a)


    enter image description here




  3. As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.



    changeReference(f);


    enter image description here




  4. Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".



    Foo b = new Foo("b");


    enter image description here




  5. a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".



    enter image description here







  6. As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".



    enter image description here




  7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's same object that reference f points to it.



    enter image description here




I hope you understand now how passing objects as arguments works in Java :)





share



















  • 57




    +1 Nice stuff. good diagrams. I also found a nice succinct page here adp-gmbh.ch/php/pass_by_reference.html OK I admit it is written in PHP, but it is the priciple of understanding the difference that I think is important (and how to manipulate that difference to your needs).
    – DaveM
    Jun 7 '13 at 8:46






  • 3




    @Eng.Fouad It's a nice explanation but if a points to the same object as f (and never gets its own copy of the object f points to), any changes to the object made using a should modify f aswell (since they are both working with the same object), so at some point a must get its own copy of the object f points to.
    – Mr D
    Jul 15 '13 at 19:08






  • 10




    @MrD when 'a' points to the same object 'f' also points to, then any change made to that object via 'a' is also observable via 'f', BUT IT DID NOT CHANGE 'f'. 'f' still points to the same object. You can totally change the object, but you can never change what 'f' points to. This is the fundamental issue that for some reason some people just can't comprehend.
    – Mike Braun
    Dec 1 '13 at 13:02










  • @MikeBraun ...what? Now you've confused me :S. Isn't what you just wrote contrary to what 6. and 7. shows?
    – Evil Washing Machine
    Nov 18 '14 at 11:34






  • 4




    This is the best explanation I've found. By the way, what about the basic situation? For example, the argument requires an int type, does it still pass the copy of an int variable to the argument?
    – allenwang
    May 21 '16 at 12:38


















up vote
671
down vote













This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you'll just smile :-)



Step one please erase from your mind that word that starts with 'p' "_ _ _ _ _ _ _", especially if you come from other programming languages. Java and 'p' cannot be written in the same book, forum, or even txt.



Step two remember that when you pass an Object into a method you're passing the Object reference and not the Object itself.





  • Student: Master, does this mean that Java is pass-by-reference?


  • Master: Grasshopper, No.


Now think of what an Object's reference/variable does/is:




  1. A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).

  2. When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.

  3. So you're just passing 3bad086a that it's the value of the reference.

  4. You're passing the value of the reference and not the reference itself (and not the object).


  5. This value is actually COPIED and given to the method.


In the following (please don't try to compile/execute this...):



1. Person person;
2. person = new Person("Tom");
3. changeName(person);
4.
5. //I didn't use Person person below as an argument to be nice
6. static void changeName(Person anotherReferenceToTheSamePersonObject) {
7. anotherReferenceToTheSamePersonObject.setName("Jerry");
8. }


What happens?




  • The variable person is created in line #1 and it's null at the beginning.

  • A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is, its address. Let's say 3bad086a.

  • The variable person holding the address of the Object is passed to the function in line #3.

  • In line #4 you can listen to the sound of silence

  • Check the comment on line #5

  • A method local variable -anotherReferenceToTheSamePersonObject- is created and then comes the magic in line #6:


    • The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.

    • No new instances of Person are created.

    • Both "person" and "anotherReferenceToTheSamePersonObject" hold the same value of 3bad086a.

    • Don't try this but person==anotherReferenceToTheSamePersonObject would be true.

    • Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.




A picture is worth a thousand words:



Pass by Value



Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!



If you didn't get it then just trust me and remember that it's better to say that Java is pass by value. Well, pass by reference value. Oh well, even better is pass-by-copy-of-the-variable-value! ;)



Now feel free to hate me but note that given this there is no difference between passing primitive data types and Objects when talking about method arguments.



You always pass a copy of the bits of the value of the reference!




  • If it's a primitive data type these bits will contain the value of the primitive data type itself.

  • If it's an Object the bits will contain the value of the address that tells the JVM how to get to the Object.



Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you'll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!







The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.






Of course you can cut it short and just say that Java is pass-by-value!





share



















  • 5




    Do you mean pointers?.. If I get it correctly, in public void foo(Car car){ ... }, car is local to foo and it contains the heap location of the Object? So if I change car's value by car = new Car(), it will point to different Object on the heap? and if I change car's property valu by car.Color = "Red", the Object in the heap pointed by car will be modified. Also, it is the same in C#? Please reply! Thanks!
    – dpp
    Feb 25 '12 at 3:29






  • 9




    @domanokz You're killing me, please don't say that word again! ;) Note that I could have answered this question without saying 'reference' as well. It's a terminology issue and 'p's make it worse. Me and Scot have different views on this unfortunately. I think you got how it works in Java, now you can call it pass by-value, by-object-sharing, by-copy-of-the-variable-value, or feel free to come up with something else! I don't really care as long as you got how it works and what's in a variable of type Object: just a PO Box address! ;)
    – Gevorg
    Feb 25 '12 at 21:25






  • 8




    Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
    – John Strickler
    Mar 12 '14 at 17:38






  • 3




    I guess Java designed with pointers in mind. Otherwise, why NullPointerException exists? Nevertheless, for this wonderful explanantion, getting pointers will just make it complicated
    – brain storm
    Aug 20 '14 at 17:42






  • 3




    So drop in on theoretical line #9 System.out.println(person.getName()); what will show up? "Tom" or "Jerry"? This is the last thing that will help me hurdle this confusion.
    – TheBrenny
    Oct 19 '14 at 12:20


















up vote
582
down vote













Java is always pass by value, with no exceptions, ever.



So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java never provides direct access to the values of objects themselves, in any circumstances. The only access to objects is through a reference to that object. Because Java objects are always accessed through a reference, rather than directly, it is common to talk about fields and variables and method arguments as being objects, when pedantically they are only references to objects. The confusion stems from this (strictly speaking, incorrect) change in nomenclature.



So, when calling a method




  • For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive (for example, 3).

  • For objects, the pass by value is the value of the reference to the object.


So if you have doSomething(foo) and public void doSomething(Foo foo) { .. } the two Foos have copied references that point to the same objects.



Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.





share



















  • 7




    Since the values of the primitives are immutable (like String), the difference between the two cases is not really relevant.
    – Paŭlo Ebermann
    Feb 3 '11 at 1:23






  • 4




    Exactly. For all you can tell via observable JVM behavior, primitives could be being passed by reference and could live on the heap. They don't, but that's not actually observable in any way.
    – Gravity
    Jul 31 '11 at 4:50






  • 5




    primitives are immutable? is that new in Java 7?
    – Carlos Heuberger
    Aug 22 '11 at 11:26






  • 2




    @CarlosHeuberger, "primitives are immutable?". The point is that you can pretend that 'primitives' are actually (mutable) references to immutable objects.
    – Aaron McDaid
    Jul 30 '15 at 16:29






  • 4




    Pointers are immutable, primitives in general are mutable. String is also not a primitive, it is an object. Moreover, the underlying structure of the String is a mutable array. The only immutable thing about it is the length, that being the inherent nature of arrays.
    – kingfrito_5005
    Aug 12 '15 at 18:44


















up vote
285
down vote













Java passes references by value.



So you can't change the reference that gets passed in.





share



















  • 25




    But the thing that keeps getting repeated "you can't change the value of objects passed in arguments" is clearly false. You may not be able to make them refer to a different object, but you can change their contents by calling their methods. IMO this means you lose all the benefits of references, and gain no additional guarantees.
    – Timmmm
    Jul 24 '11 at 19:13






  • 31




    I never said "you can't change the value of objects passed in arguments". I will say "You can't change the value of the object reference passed in as a method argument", which is a true statement about the Java language. Obviously you can change the state of the object (as long as it's not immutable).
    – ScArcher2
    Aug 1 '11 at 14:19








  • 16




    Keep in mind that you cannot actually pass objects in java; the objects stay on the heap. Pointers to the objects can be passed (which get copied onto the stack frame for the called method). So you never change the passed-in value (the pointer), but you're free to follow it and change the thing on the heap to which it points. That's pass-by-value.
    – Scott Stanchfield
    Jan 26 '12 at 22:17






  • 5




    Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
    – John Strickler
    Mar 12 '14 at 17:38






  • 2




    Java does not pass an object, it passes the value of the pointer to the object. This creates a new pointer to that memory location of the original object in a new variable. If you change the value (the memory address it points to) of this pointer variable in a method, then the original pointer used in the method caller remains unmodified. If you are calling the parameter a reference then the fact that it is a copy of the original reference, not the original reference itself such that there are now two references to the object means that it is pass-by-value
    – theferrit32
    Nov 19 '14 at 16:38




















up vote
205
down vote













I feel like arguing about "pass-by-reference vs pass-by-value" is not super-helpful.



If you say, "Java is pass-by-whatever (reference/value)", in either case, you're not provide a complete answer. Here's some additional information that will hopefully aid in understanding what's happening in memory.



Crash course on stack/heap before we get to the Java implementation:
Values go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria.
Memory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.



Okay. First off, local primitives go on the stack. So this code:



int x = 3;
float y = 101.1f;
boolean amIAwesome = true;


results in this:



primitives on the stack



When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word "pointer". Whatever. Just know that the address of the object goes on the stack.



Like so:



int problems = 99;
String name = "Jay-Z";


a b*7ch aint one!



An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.



JButton marxBros = new JButton[3];
marxBros[0] = new JButton("Groucho");
marxBros[1] = new JButton("Zeppo");
marxBros[2] = new JButton("Harpo");


marx brothers



So, what gets passed in when you call a method? If you pass in an object, what you're actually passing in is the address of the object. Some might say the "value" of the address, and some say it's just a reference to the object. This is the genesis of the holy war between "reference" and "value" proponents. What you call it isn't as important as that you understand that what's getting passed in is the address to the object.



private static void shout(String name){
System.out.println("There goes " + name + "!");
}

public static void main(String args){
String hisName = "John J. Jingleheimerschmitz";
String myName = hisName;
shout(myName);
}


One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier hisName, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call shout(): a new stack frame is created and a new identifier, name is created and assigned the address of the already-existing String.



la da di da da da da



So, value, reference? You say "potato".





share



















  • 6




    However, you should have followed up with a more complex example where a function appears to alter a variable to whose address it has a reference.
    – Brian Peterson
    Nov 1 '13 at 6:53






  • 28




    People are not "dancing around the real issue" of stack vs heap, because that's not the real issue. It's an implementation detail at best, and downright wrong at worst. (It's quite possible for objects to live on the stack; google "escape analysis". And a huge number of objects contain primitives that probably don't live on the stack.) The real issue is exactly the difference between reference types and value types -- in particular, that the value of a reference-type variable is a reference, not the object it refers to.
    – cHao
    Dec 18 '13 at 4:48








  • 8




    It's an "implementation detail" in that Java is never required to actually show you where an object lives in memory, and in fact seems determined to avoid leaking that info. It could put the object on the stack, and you'd never know. If you care, you're focusing on the wrong thing -- and in this case, that means ignoring the real issue.
    – cHao
    Dec 18 '13 at 14:38








  • 9




    And either way, "primitives go on the stack" is incorrect. Primitive local variables go on the stack. (If they haven't been optimized away, of course.) But then, so do local reference variables. And primitive members defined within an object live wherever the object lives.
    – cHao
    Dec 18 '13 at 14:55








  • 9




    Agree with the comments here. Stack/heap is a side issue, and not relevant. Some variables may be on the stack, some are in static memory (static variables), and plenty live on the heap (all object member variables). NONE of these variables can be passed by reference: from a called method it is NEVER possible to change the value of a variable that is passed as an argument. Therefore, there is no pass-by-reference in Java.
    – fishinear
    Mar 2 '14 at 15:37


















up vote
168
down vote













Just to show the contrast, compare the following C++ and Java snippets:



In C++: Note: Bad code - memory leaks! But it demonstrates the point.



void cppMethod(int val, int &ref, Dog obj, Dog &objRef, Dog *objPtr, Dog *&objPtrRef)
{
val = 7; // Modifies the copy
ref = 7; // Modifies the original variable
obj.SetName("obj"); // Modifies the copy of Dog passed
objRef.SetName("objRef"); // Modifies the original Dog passed
objPtr->SetName("objPtr"); // Modifies the original Dog pointed to
// by the copy of the pointer passed.
objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
// leaving the original object alone.
objPtrRef->SetName("objRefPtr"); // Modifies the original Dog pointed to
// by the original pointer passed.
objPtrRef = new Dog("newObjPtrRef"); // Modifies the original pointer passed
}

int main()
{
int a = 0;
int b = 0;
Dog d0 = Dog("d0");
Dog d1 = Dog("d1");
Dog *d2 = new Dog("d2");
Dog *d3 = new Dog("d3");
cppMethod(a, b, d0, d1, d2, d3);
// a is still set to 0
// b is now set to 7
// d0 still have name "d0"
// d1 now has name "objRef"
// d2 now has name "objPtr"
// d3 now has name "newObjPtrRef"
}


In Java,



public static void javaMethod(int val, Dog objPtr)
{
val = 7; // Modifies the copy
objPtr.SetName("objPtr") // Modifies the original Dog pointed to
// by the copy of the pointer passed.
objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
// leaving the original object alone.
}

public static void main()
{
int a = 0;
Dog d0 = new Dog("d0");
javaMethod(a, d0);
// a is still set to 0
// d0 now has name "objPtr"
}


Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.





share



















  • 7




    +1 I would also add Dog **objPtrPtr to the C++ example, that way we can modify what the pointer "points to".
    – Amro
    Jul 2 '14 at 3:59










  • This is one of the best answers I have seen so far. It mostly avoids the irrelevant semantics argument of "reference vs value of the reference" present elsewhere and instead discusses the mechanics of what actually happens. I had to give most other "pass-by-value" answers -1 because of their self-contradictory or factually false content, but this one gets +1 instead.
    – Aaron
    Aug 2 '17 at 15:32










  • But this doesn't answer for the given question in Java. As the matter of fact, everything in Java's method is Pass By Value, nothing more.
    – tauitdnmd
    Nov 6 at 9:11


















up vote
147
down vote













Java passes references to objects by value.





share























  • As simple as that !
    – Ivan Kaloyanov
    May 30 at 10:39


















up vote
140
down vote













Basically, reassigning Object parameters doesn't affect the argument, e.g.,



private void foo(Object bar) {
bar = null;
}

public static void main(String args) {
String baz = "Hah!";
foo(baz);
System.out.println(baz);
}


will print out "Hah!" instead of null. The reason this works is because bar is a copy of the value of baz, which is just a reference to "Hah!". If it were the actual reference itself, then foo would have redefined baz to null.





share



















  • 7




    I would rather say that bar is a copy of the reference baz (or baz alias), that points initially to the same object.
    – MaxZoom
    Feb 11 '15 at 5:36


















up vote
139
down vote













I can't believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term call by sharing (also known as call by object-sharing and call by object) for this specific case of "call by value where the value is a reference".





share



















  • 2




    I like this distinction in nomenclature. It's unfortunate that Java supports call by sharing for objects, but not call by value (as does C++). Java supports call by value only for primitive data types and not composite data types.
    – Derek Mahar
    Sep 8 '10 at 14:16






  • 2




    I really don't think we needed an extra term - it's simply pass-by-value for a specific type of value. Would adding "call by primitive" add any clarification?
    – Scott Stanchfield
    Oct 25 '10 at 20:03






  • 7




    Call by Sharing
    – wulfgarpro
    Sep 16 '11 at 0:29












  • So I can pass-by-reference by sharing some global context object, or even passing a context object that contains other references? I still pass-by-value, but at least I have access to references I can modify and make them point to something else.
    – YoYo
    Jan 8 '16 at 0:14


















up vote
99
down vote













The crux of the matter is that the word reference in the expression "pass by reference" means something completely different from the usual meaning of the word reference in Java.



Usually in Java reference means a a reference to an object. But the technical terms pass by reference/value from programming language theory is talking about a reference to the memory cell holding the variable, which is something completely different.





share



















  • 10




    Colloquially called a pointer.
    – Prof. Falken
    Feb 9 '11 at 9:50






  • 7




    @Gevorg - Then what is a "NullPointerException"?
    – Hot Licks
    Sep 22 '13 at 14:09






  • 4




    @Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException.
    – JacquesB
    Sep 23 '13 at 14:08






  • 4




    It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding.
    – Hot Licks
    Sep 23 '13 at 15:46










  • I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity.
    – moronkreacionz
    Dec 29 '15 at 21:36


















up vote
75
down vote













In java everything is reference, so when you have something like:
Point pnt1 = new Point(0,0); Java does following:




  1. Creates new Point object

  2. Creates new Point reference and initialize that reference to point (refer to) on previously created Point object.

  3. From here, through Point object life, you will access to that object through pnt1
    reference. So we can say that in Java you manipulate object through its reference.



enter image description here



Java doesn't pass method arguments by reference; it passes them by value. I will use example from this site:



public static void tricky(Point arg1, Point arg2) {
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String args) {
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y);
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
}


Flow of the program:



Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);


Creating two different Point object with two different reference associated.
enter image description here



System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y); 
System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
System.out.println(" ");


As expected output will be:



X1: 0     Y1: 0
X2: 0 Y2: 0


On this line 'pass-by-value' goes into the play...



tricky(pnt1,pnt2);           public void tricky(Point arg1, Point arg2);


References pnt1 and pnt2 are passed by value to the tricky method, which means that now yours references pnt1 and pnt2 have their copies named arg1 and arg2.So pnt1 and arg1 points to the same object. (Same for the pnt2 and arg2)
enter image description here



In the tricky method:



 arg1.x = 100;
arg1.y = 100;


enter image description here



Next in the tricky method



Point temp = arg1;
arg1 = arg2;
arg2 = temp;


Here, you first create new temp Point reference which will point on same place like arg1 reference. Then you move reference arg1 to point to the same place like arg2 reference.
Finally arg2 will point to the same place like temp.



enter image description here



From here scope of tricky method is gone and you don't have access any more to the references: arg1, arg2, temp. But important note is that everything you do with these references when they are 'in life' will permanently affect object on which they are point to.



So after executing method tricky, when you return to main, you have this situation:
enter image description here



So now, completely execution of program will be:



X1: 0         Y1: 0
X2: 0 Y2: 0
X1: 100 Y1: 100
X2: 0 Y2: 0




share



















  • 7




    In java when you say "In java everything is reference" you mean all objects are passed by reference. Primitive data types are not passed by reference.
    – Eric
    Oct 22 '15 at 6:42










  • I am able to print swapped value in main method. in trickey method , add the following statement arg1.x = 1; arg1.y = 1; arg2.x = 2; arg2.y = 2; so, as arg1 now holding of pnt2 refrence and arg2 holding now pnt1 reference, so, its printing X1: 2 Y1: 2 X2: 1 Y2: 1
    – Shahid Ghafoor
    Dec 20 '16 at 1:29




















up vote
64
down vote













A reference is always a value when represented, no matter what language you use.



Getting an outside of the box view, let's look at Assembly or some low level memory management. At the CPU level a reference to anything immediately becomes a value if it gets written to memory or to one of the CPU registers. (That is why pointer is a good definition. It is a value, which has a purpose at the same time).



Data in memory has a Location and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a Name to certain Location (aka variable), but when compiling the code, the assembler simply replaces Name with the designated location just like your browser replaces domain names with IP addresses.



Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).



Lets say we have a variable Foo, its Location is at the 47th byte in memory and its Value is 5. We have another variable Ref2Foo which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two Values.
If you use them as references then to reach to 5 we have to travel:



(Name)[Location] -> [Value at the Location]
---------------------
(Ref2Foo)[223] -> 47
(Foo)[47] -> 5


This is how jump-tables work.



If we want to call a method/function/procedure with Foo's value, there are a few possible way to pass the variable to the method, depending on the language and its several method invocation modes:




  1. 5 gets copied to one of the CPU registers (ie. EAX).

  2. 5 gets PUSHd to the stack.

  3. 47 gets copied to one of the CPU registers

  4. 47 PUSHd to the stack.

  5. 223 gets copied to one of the CPU registers.

  6. 223 gets PUSHd to the stack.


In every cases above a value - a copy of an existing value - has been created, it is now upto the receiving method to handle it. When you write "Foo" inside the method, it is either read out from EAX, or automatically dereferenced, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a reference is a value when represented, because a reference is a value that has to be processed (at language level).



Now we have passed Foo to the method:




  • in case 1. and 2. if you change Foo (Foo = 9) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.

  • in case 3. and 4. if you use default language constructs and change Foo (Foo = 11), it could change Foo globally (depends on the language, ie. Java or like Pascal's procedure findMin(x, y, z: integer;var m: integer);). However if the language allows you to circumvent the dereference process, you can change 47, say to 49. At that point Foo seems to have been changed if you read it, because you have changed the local pointer to it. And if you were to modify this Foo inside the method (Foo = 12) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at 47). BUT Foo's value of 47 did not change globally, only the one inside the method, because 47 was also a copy to the method.

  • in case 5. and 6. if you modify 223 inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was copied. However if you are able to dereference Ref2Foo (that is 223), reach to and modify the pointed value 47, say, to 49, it will affect Foo globally, because in this case the methods got a copy of 223 but the referenced 47 exists only once, and changing that to 49 will lead every Ref2Foo double-dereferencing to a wrong value.


Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only pass-by-reference.



Strict pass-by-value is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller's view) and a few languages allows to modify the Value of the reference itself.



So in short and in Java's own terminology, Java is pass-by-value where value can be: either a real value or a value that is a representation of a reference.





share























  • In a language with pass-by-reference, the thing which is passed (the reference) is ephemeral; the recipient is not "supposed" to copy it. In Java, passing an array is passed is an "object identifier"--equivalent to a slip of paper which says "Object #24601", when the 24601st object constructed was an array. The recipient can copy "Object #24601" anywhere it wants, and anyone with a slip of paper saying "Object #24601" can do anything it wants with any of the array elements. The pattern of bits that is passed wouldn't actually say "Object #24601", of course, but...
    – supercat
    Jan 10 '14 at 17:02










  • ...the key point is that the recipient of the object-id that identifies the array can store that object-id wherever it wants and give it to whomever it wants, and any recipient would be able to access or modify the array whenever it wants. By contrast, if an array were passed by reference in a language like Pascal which supports such things, the called method could do whatever it wanted with the array, but could not store the reference in such a way as to allow code to modify the array after it returned.
    – supercat
    Jan 10 '14 at 17:04










  • Indeed, in Pascal you can get the address of every variable, be it passed-by-reference or locally copied, addr does it untyped,@ does it with type, and you can modify the referenced variable later (except locally copied ones). But I don't see the point why you would do that. That slip of paper in your example (Object #24601) is a reference,its purpose is to help find the array in memory, it does not contain any array data in itself. If you restart your program, the same array might get a different object-id even if its content will be the same as it has been in the previous run.
    – karatedog
    Jan 10 '14 at 22:48










  • I'd thought the "@" operator was not part of standard Pascal, but was implemented as a common extension. Is it part of the standard? My point was that in a language with true pass-by-ref, and no ability to construct a non-ephemeral pointer to an ephemeral object, code which holds the only reference to an array, anywhere in the universe, before passing the array by reference can know that unless the recipient "cheats" it will still hold the only reference afterward. The only safe way to accomplish that in Java would be to construct a temporary object...
    – supercat
    Jan 10 '14 at 22:52










  • ...which encapsulates an AtomicReference and neither exposes the reference nor its target, but instead includes methods to do things to the target; once the code to which the object was passed returns, the AtomicReference [to which its creator kept a direct reference] should be invalidated and abandoned. That would provide the proper semantics, but it would be slow and icky.
    – supercat
    Jan 10 '14 at 22:54


















up vote
64
down vote













Java is always pass by value, not pass by reference



First of all, we need to understand what pass by value and pass by reference are.



Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.



Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.



Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:



public class PassByValue {
public static void main(String args) {
Test t = new Test();
t.name = "initialvalue";
new PassByValue().changeValue(t);
System.out.println(t.name);
}

public void changeValue(Test f) {
f.name = "changevalue";
}
}

class Test {
String name;
}


The output of this program is:




changevalue



Let's understand step by step:



Test t = new Test();


As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .



first illustration



new PassByValue().changeValue(t);


When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.



second illustration



If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.



To understand this more clearly, consider the following example:



public class PassByValue {
public static void main(String args) {
Test t = new Test();
t.name = "initialvalue";
new PassByValue().changeRefence(t);
System.out.println(t.name);
}

public void changeRefence(Test f) {
f = null;
}
}

class Test {
String name;
}


Will this throw a NullPointerException? No, because it only passes a copy of the reference.
In the case of passing by reference, it could have thrown a NullPointerException, as seen below:



third illustration



Hopefully this will help.





share























  • Excellent answer, the key statement: "When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function"
    – pedram bashiri
    May 4 at 16:25


















up vote
50
down vote













As far as I know, Java only knows call by value. This means for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects. However I think there are some pitfalls; for example, this will not work:



public static void swap(StringBuffer s1, StringBuffer s2) {
StringBuffer temp = s1;
s1 = s2;
s2 = temp;
}


public static void main(String args) {
StringBuffer s1 = new StringBuffer("Hello");
StringBuffer s2 = new StringBuffer("World");
swap(s1, s2);
System.out.println(s1);
System.out.println(s2);
}


This will populate Hello World and not World Hello because in the swap function you use copys which have no impact on the references in the main. But if your objects are not immutable you can change it for example:



public static void appendWorld(StringBuffer s1) {
s1.append(" World");
}

public static void main(String args) {
StringBuffer s = new StringBuffer("Hello");
appendWorld(s);
System.out.println(s);
}


This will populate Hello World on the command line. If you change StringBuffer into String it will produce just Hello because String is immutable. For example:



public static void appendWorld(String s){
s = s+" World";
}

public static void main(String args) {
String s = new String("Hello");
appendWorld(s);
System.out.println(s);
}


However you could make a wrapper for String like this which would make it able to use it with Strings:



class StringWrapper {
public String value;

public StringWrapper(String value) {
this.value = value;
}
}

public static void appendWorld(StringWrapper s){
s.value = s.value +" World";
}

public static void main(String args) {
StringWrapper s = new StringWrapper("Hello");
appendWorld(s);
System.out.println(s.value);
}


edit: i believe this is also the reason to use StringBuffer when it comes to "adding" two Strings because you can modifie the original object which u can't with immutable objects like String is.





share























  • +1 for the swap test -- probably the most straightforward and relatable way to distinguish between passing by reference and passing a reference by value. Iff you can easily write a function swap(a, b) that (1) swaps a and b from the caller's POV, (2) is type-agnostic to the extent that static typing allows (meaning using it with another type requires nothing more than changing the declared types of a and b), and (3) doesn't require the caller to explicitly pass a pointer or name, then the language supports passing by reference.
    – cHao
    Dec 17 '13 at 21:24










  • "..for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects" - perfectly written!
    – Raúl
    Nov 24 '16 at 13:16


















up vote
50
down vote













No, it's not pass by reference.



Java is pass by value according to 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.






share






























    up vote
    46
    down vote













    Let me try to explain my understanding with the help of four examples. Java is pass-by-value, and not pass-by-reference



    /**



    Pass By Value



    In Java, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.



    */



    Example 1:



    public class PassByValueString {
    public static void main(String args) {
    new PassByValueString().caller();
    }

    public void caller() {
    String value = "Nikhil";
    boolean valueflag = false;
    String output = method(value, valueflag);
    /*
    * 'output' is insignificant in this example. we are more interested in
    * 'value' and 'valueflag'
    */
    System.out.println("output : " + output);
    System.out.println("value : " + value);
    System.out.println("valueflag : " + valueflag);

    }

    public String method(String value, boolean valueflag) {
    value = "Anand";
    valueflag = true;
    return "output";
    }
    }


    Result



    output : output
    value : Nikhil
    valueflag : false


    Example 2:



    /**
    *
    * Pass By Value
    *
    */



    public class PassByValueNewString {
    public static void main(String args) {
    new PassByValueNewString().caller();
    }

    public void caller() {
    String value = new String("Nikhil");
    boolean valueflag = false;
    String output = method(value, valueflag);
    /*
    * 'output' is insignificant in this example. we are more interested in
    * 'value' and 'valueflag'
    */
    System.out.println("output : " + output);
    System.out.println("value : " + value);
    System.out.println("valueflag : " + valueflag);

    }

    public String method(String value, boolean valueflag) {
    value = "Anand";
    valueflag = true;
    return "output";
    }
    }


    Result



    output : output
    value : Nikhil
    valueflag : false


    Example 3:



    /**
    This 'Pass By Value has a feeling of 'Pass By Reference'



    Some people say primitive types and 'String' are 'pass by value'
    and objects are 'pass by reference'.



    But from this example, we can understand that it is infact pass by value only,
    keeping in mind that here we are passing the reference as the value.
    ie: reference is passed by value.
    That's why are able to change and still it holds true after the local scope.
    But we cannot change the actual reference outside the original scope.
    what that means is demonstrated by next example of PassByValueObjectCase2.



    */



    public class PassByValueObjectCase1 {

    private class Student {
    int id;
    String name;
    public Student() {
    }
    public Student(int id, String name) {
    super();
    this.id = id;
    this.name = name;
    }
    public int getId() {
    return id;
    }
    public void setId(int id) {
    this.id = id;
    }
    public String getName() {
    return name;
    }
    public void setName(String name) {
    this.name = name;
    }
    @Override
    public String toString() {
    return "Student [id=" + id + ", name=" + name + "]";
    }
    }

    public static void main(String args) {
    new PassByValueObjectCase1().caller();
    }

    public void caller() {
    Student student = new Student(10, "Nikhil");
    String output = method(student);
    /*
    * 'output' is insignificant in this example. we are more interested in
    * 'student'
    */
    System.out.println("output : " + output);
    System.out.println("student : " + student);
    }

    public String method(Student student) {
    student.setName("Anand");
    return "output";
    }
    }


    Result



    output : output
    student : Student [id=10, name=Anand]


    Example 4:



    /**



    In addition to what was mentioned in Example3 (PassByValueObjectCase1.java), we cannot change the actual reference outside the original scope."



    Note: I am not pasting the code for private class Student. The class definition for Student is same as Example3.



    */



    public class PassByValueObjectCase2 {

    public static void main(String args) {
    new PassByValueObjectCase2().caller();
    }

    public void caller() {
    // student has the actual reference to a Student object created
    // can we change this actual reference outside the local scope? Let's see
    Student student = new Student(10, "Nikhil");
    String output = method(student);
    /*
    * 'output' is insignificant in this example. we are more interested in
    * 'student'
    */
    System.out.println("output : " + output);
    System.out.println("student : " + student); // Will it print Nikhil or Anand?
    }

    public String method(Student student) {
    student = new Student(20, "Anand");
    return "output";
    }

    }


    Result



    output : output
    student : Student [id=10, name=Nikhil]




    share






























      up vote
      44
      down vote













      You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:



      void getValues(int& arg1, int& arg2) {
      arg1 = 1;
      arg2 = 2;
      }
      void caller() {
      int x;
      int y;
      getValues(x, y);
      cout << "Result: " << x << " " << y << endl;
      }


      Sometimes you want to use the same pattern in Java, but you can't; at least not directly. Instead you could do something like this:



      void getValues(int arg1, int arg2) {
      arg1[0] = 1;
      arg2[0] = 2;
      }
      void caller() {
      int x = new int[1];
      int y = new int[1];
      getValues(x, y);
      System.out.println("Result: " + x[0] + " " + y[0]);
      }


      As was explained in previous answers, in Java you're passing a pointer to the array as a value into getValues. That is enough, because the method then modifies the array element, and by convention you're expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn't necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.





      share






























        up vote
        44
        down vote













        Java is a call by value.



        How it works




        • You always pass a copy of the bits of the value of the reference!


        • If it's a primitive data type these bits contain the value of the primitive data type itself, That's why if we change the value of header inside the method then it does not reflect the changes outside.


        • If it's an object data type like Foo foo=new Foo() then in this case copy of the address of the object passes like file shortcut , suppose we have a text file abc.txt at C:desktop and suppose we make shortcut of the same file and put this inside C:desktopabc-shortcut so when you access the file from C:desktopabc.txt and write 'Stack Overflow' and close the file and again you open the file from shortcut then you write ' is the largest online community for programmers to learn' then total file change will be 'Stack Overflow is the largest online community for programmers to learn' which means it doesn't matter from where you open the file , each time we were accessing the same file , here we can assume Foo as a file and suppose foo stored at 123hd7h(original address like C:desktopabc.txt ) address and 234jdid(copied address like C:desktopabc-shortcut which actually contains the original address of the file inside) ..
          So for better understanding make shortcut file and feel...






        share






























          up vote
          43
          down vote













          I thought I'd contribute this answer to add more details from the Specifications.



          First, What's the difference between passing by reference vs. passing by value?




          Passing by reference means the called functions' parameter will be the
          same as the callers' passed argument (not the value, but the identity
          - the variable itself).



          Pass by value means the called functions' parameter will be a copy of
          the callers' passed argument.




          Or from wikipedia, on the subject of pass-by-reference




          In call-by-reference evaluation (also referred to as
          pass-by-reference), a function receives an implicit reference to a
          variable used as argument, rather than a copy of its value. This
          typically means that the function can modify (i.e. assign to) the
          variable used as argument—something that will be seen by its caller.




          And on the subject of pass-by-value




          In call-by-value, the argument expression is evaluated, and the
          resulting value is bound to the corresponding variable in the function [...].
          If the function or procedure is able to assign values to its
          parameters, only its local copy is assigned [...].




          Second, we need to know what Java uses in its method invocations. The Java Language Specification states




          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.




          So it assigns (or binds) the value of the argument to the corresponding parameter variable.



          What is the value of the argument?



          Let's consider reference types, the Java Virtual Machine Specification states




          There are three kinds of reference types: class types, array types,
          and interface types. Their values are references to dynamically
          created class instances, arrays, or class instances or arrays that
          implement interfaces, respectively.




          The Java Language Specification also states




          The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.




          The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (new ...) all resolve to a reference type value.



          So



          public void method (String param) {}
          ...
          String var = new String("ref");
          method(var);
          method(var.toString());
          method(new String("ref"));


          all bind the value of a reference to a String instance to the method's newly created parameter, param. This is exactly what the definition of pass-by-value describes. As such, Java is pass-by-value.



          The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation. The definition of pass-by-reference was




          This typically means that the function can modify (i.e. assign to) the
          variable used as argument—something that will be seen by its caller.




          In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. Modifying the object referenced by the variable is a different concept entirely.





          Primitive values are also defined in the Java Virtual Machine Specification, here. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).





          share























          • Thank you for beginning with a discussion of the definitions of the terms. That sets your answer apart from the crowd and is necessary for a proper understanding.
            – Aaron
            Aug 2 '17 at 15:39


















          up vote
          34
          down vote













          The distinction, or perhaps just the way I remember as I used to be under the same impression as the original poster is this: Java is always pass by value. All objects( in Java, anything except for primitives) in Java are references. These references are passed by value.





          share



















          • 2




            I find your second-to-last sentence very misleading. It's not true that "all objects in Java are references". It's only the references to those objects that are references.
            – Dawood ibn Kareem
            Jan 25 '17 at 10:09


















          up vote
          31
          down vote













          As many people mentioned it before, Java is always pass-by-value



          Here is another example that will help you understand the difference (the classic swap example):



          public class Test {
          public static void main(String args) {
          Integer a = new Integer(2);
          Integer b = new Integer(3);
          System.out.println("Before: a = " + a + ", b = " + b);
          swap(a,b);
          System.out.println("After: a = " + a + ", b = " + b);
          }

          public static swap(Integer iA, Integer iB) {
          Integer tmp = iA;
          iA = iB;
          iB = tmp;
          }
          }


          Prints:




          Before: a = 2, b = 3

          After: a = 2, b = 3




          This happens because iA and iB are new local reference variables that have the same value of the passed references (they point to a and b respectively). So, trying to change the references of iA or iB will only change in the local scope and not outside of this method.





          share























          • i understood with this answer
            – Kumaresan Perumal
            Apr 25 at 18:04


















          up vote
          30
          down vote













          Java has only pass by value. A very simple example to validate this.



          public void test() {
          MyClass obj = null;
          init(obj);
          //After calling init method, obj still points to null
          //this is because obj is passed as value and not as reference.
          }
          private void init(MyClass objVar) {
          objVar = new MyClass();
          }




          share



















          • 4




            This is the clearest, simplest way to see that Java passes by value. The value of obj (null) was passed to init, not a reference to obj.
            – David Schwartz
            Jun 10 '17 at 23:24


















          up vote
          30
          down vote













          In Java only references are passed and are passed by value:



          Java arguments are all passed by value (the reference is copied when used by the method) :



          In the case of primitive types, Java behaviour is simple:
          The value is copied in another instance of the primitive type.



          In case of Objects, this is the same:
          Object variables are pointers (buckets) holding only Object’s address that was created using the "new" keyword, and are copied like primitive types.



          The behaviour can appear different from primitive types: Because the copied object-variable contains the same address (to the same Object)
          Object's content/members might still be modified within a method and later access outside, giving the illusion that the (containing) Object itself was passed by reference.



          "String" Objects appear to be a perfect counter-example to the urban legend saying that "Objects are passed by reference":



          In effect, within a method you will never be able, to update the value of a String passed as argument:



          A String Object, holds characters by an array declared final that can't be modified.
          Only the address of the Object might be replaced by another using "new".
          Using "new" to update the variable, will not let the Object be accessed from outside, since the variable was initially passed by value and copied.





          share























          • So it's byRef in regards to objects and byVal in regards to primitives?
            – Mox
            Jan 18 '17 at 11:40










          • @mox please read: Objects are not passed by reference, this is a ledgend: String a=new String("unchanged");
            – user1767316
            Jan 25 '17 at 23:28












          • public void changeit(String changeit){changit = "changed";} changeIt(a); assert(a.equals("unchanged"));
            – user1767316
            Jan 25 '17 at 23:35










          • This is yet another great example of the fallacy of the "it is not pass by reference" semantics argument. This answer says right in the bold, first sentence: "only references are passed." Either a reference is passed, or a reference is not passed. You just said yourself that a reference is passed. By saying "it is not passed by reference since a reference is passed but..." you are trying to make a point by mangling English.
            – Aaron
            Aug 2 '17 at 15:07










          • @Aaron "Pass by reference" does not mean "pass a value that is a member of a type that is called a 'reference' in Java". The two uses of "reference" mean different things.
            – philipxy
            Sep 27 '17 at 8:36




















          up vote
          29
          down vote













          I always think of it as "pass by copy". It is a copy of the value be it primitive or reference. If it is a primitive it is a copy of the bits that are the value and if it is an Object it is a copy of the reference.



          public class PassByCopy{
          public static void changeName(Dog d){
          d.name = "Fido";
          }
          public static void main(String args){
          Dog d = new Dog("Maxx");
          System.out.println("name= "+ d.name);
          changeName(d);
          System.out.println("name= "+ d.name);
          }
          }
          class Dog{
          public String name;
          public Dog(String s){
          this.name = s;
          }
          }


          output of java PassByCopy:




          name= Maxx

          name= Fido




          Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.





          share



















          • 3




            "pass by copy" is what pass-by-value means.
            – T.J. Crowder
            Aug 7 '16 at 8:46


















          up vote
          24
          down vote













          I have created a thread devoted to these kind of questions for any programming languages here.



          Java is also mentioned. Here is the short summary:




          • Java passes it parameters by value

          • "by value" is the only way in java to pass a parameter to a method

          • using methods from the object given as parameter will alter the
            object as the references point to
            the original objects. (if that
            method itself alters some values)





          share






























            up vote
            23
            down vote













            A few corrections to some posts.



            C does NOT support pass by reference. It is ALWAYS pass by value. C++ does support pass by reference, but is not the default and is quite dangerous.



            It doesn't matter what the value is in Java: primitive or address(roughly) of object, it is ALWAYS passed by value.



            If a Java object "behaves" like it is being passed by reference, that is a property of mutability and has absolutely nothing to do with passing mechanisms.



            I am not sure why this is so confusing, perhaps because so many Java "programmers" are not formally trained, and thus do not understand what is really going on in memory?





            share



















            • 1




              +1. What C does support, is treating references (which C calls pointers) as first-class values, and then passing them by value.
              – Jörg W Mittag
              Sep 7 '10 at 22:02






            • 1




              Yeah, in C you can create pointers not only on objects, but on arbitrary variables - so you can easily simulate "call-by-reference" of any variable. In Java this works only for variables which have a surrounding object, which you can give.
              – Paŭlo Ebermann
              Feb 3 '11 at 1:27


















            up vote
            22
            down vote













            To make a long story short, Java objects have some very peculiar properties.



            In general, Java has primitive types (int, bool, char, double, etc) that are passed directly by value. Then Java has objects (everything that derives from java.lang.Object). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.



            Does this sound strange and confusing? Let's consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. void foo(int x) passes an int by value. void foo(int *x) is a function that does not want an int a, but a pointer to an int: foo(&a). One would use this with the & operator to pass a variable address.



            Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: void foo(int &x) is called by foo(a), where the compiler itself knows that it is a reference and the address of the non-reference a should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.





            share























            • I think it is very close to my understanding of Java object and its reference. Object in Java is passed to a method by a reference copy (or alias).
              – MaxZoom
              Feb 11 '15 at 5:58


















            up vote
            21
            down vote













            Java passes parameters by VALUE, and by value ONLY.



            To cut long story short:




            For those coming from C#: THERE IS NO "out" parameter.



            For those coming from PASCAL: THERE IS NO "var" parameter.




            It means you can't change the reference from the object itself, but you can always change the object's properties.



            A workaround is to use StringBuilder parameter instead String. And you can always use arrays!





            share























            • I think you nailed it by saying you can't change the reference from the object itself
              – sakhunzai
              Mar 30 '17 at 5:41










            • So an object can be changed by using its public interfaces but could not be replace with sth else i.e deference and by this java achieves best of both worlds
              – sakhunzai
              Mar 30 '17 at 6:00















            1 2
            3
            next


            protected by Nick Craver Jun 24 '11 at 18:08



            Thank you for your interest in this question.
            Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



            Would you like to answer one of these unanswered questions instead?














            77 Answers
            77






            active

            oldest

            votes








            77 Answers
            77






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            1 2
            3
            next









            up vote
            4906
            down vote



            +50










            Java is always pass-by-value. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners.



            It goes like this:



            public static void main(String args) {
            Dog aDog = new Dog("Max");
            // we pass the object to foo
            foo(aDog);
            // aDog variable is still pointing to the "Max" dog when foo(...) returns
            aDog.getName().equals("Max"); // true
            aDog.getName().equals("Fifi"); // false
            }

            public static void foo(Dog d) {
            d.getName().equals("Max"); // true
            // change d inside of foo() to point to a new Dog instance "Fifi"
            d = new Dog("Fifi");
            d.getName().equals("Fifi"); // true
            }


            In the example above aDog.getName() will still return "Max". The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.



            Likewise:



            public static void main(String args) {
            Dog aDog = new Dog("Max");
            foo(aDog);
            // when foo(...) returns, the name of the dog has been changed to "Fifi"
            aDog.getName().equals("Fifi"); // true
            }

            public static void foo(Dog d) {
            d.getName().equals("Max"); // true
            // this changes the name of d to be "Fifi"
            d.setName("Fifi");
            }


            In the above example, Fifi is the dog's name after call to foo(aDog) because the object's name was set inside of foo(...). Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog itself (except when d is changed to point to a different Dog instance like d = new Dog("Boxer")).





            share



















            • 219




              Isn't it slightly confusing the issue with internal details? There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'.
              – izb
              Sep 8 '08 at 14:58






            • 336




              But there is a subtle difference. Look at the first example. If it was purely pass by reference, aDog.name would be "Fifi". It isn't - the reference you are getting is a value reference that if overwritten will be restored when exiting the function.
              – erlando
              Sep 11 '08 at 6:55






            • 264




              @Lorenzo: No, in Java everything is passed by value. Primitives are passed by value, and object references are passed by value. The objects themselves are never passed to a method, but the objects are always in the heap and only a reference to the object is passed to the method.
              – Esko Luontola
              Feb 12 '09 at 23:02






            • 258




              My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed.
              – dhackner
              Oct 20 '10 at 16:38








            • 126




              What's confusing is that object references are actually pointers. In the beginning SUN called them pointers. Then marketing informed that "pointer" was a bad word. But you still see the "correct" nomenclature in NullPointerException.
              – Prof. Falken
              Feb 9 '11 at 9:46

















            up vote
            4906
            down vote



            +50










            Java is always pass-by-value. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners.



            It goes like this:



            public static void main(String args) {
            Dog aDog = new Dog("Max");
            // we pass the object to foo
            foo(aDog);
            // aDog variable is still pointing to the "Max" dog when foo(...) returns
            aDog.getName().equals("Max"); // true
            aDog.getName().equals("Fifi"); // false
            }

            public static void foo(Dog d) {
            d.getName().equals("Max"); // true
            // change d inside of foo() to point to a new Dog instance "Fifi"
            d = new Dog("Fifi");
            d.getName().equals("Fifi"); // true
            }


            In the example above aDog.getName() will still return "Max". The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.



            Likewise:



            public static void main(String args) {
            Dog aDog = new Dog("Max");
            foo(aDog);
            // when foo(...) returns, the name of the dog has been changed to "Fifi"
            aDog.getName().equals("Fifi"); // true
            }

            public static void foo(Dog d) {
            d.getName().equals("Max"); // true
            // this changes the name of d to be "Fifi"
            d.setName("Fifi");
            }


            In the above example, Fifi is the dog's name after call to foo(aDog) because the object's name was set inside of foo(...). Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog itself (except when d is changed to point to a different Dog instance like d = new Dog("Boxer")).





            share



















            • 219




              Isn't it slightly confusing the issue with internal details? There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'.
              – izb
              Sep 8 '08 at 14:58






            • 336




              But there is a subtle difference. Look at the first example. If it was purely pass by reference, aDog.name would be "Fifi". It isn't - the reference you are getting is a value reference that if overwritten will be restored when exiting the function.
              – erlando
              Sep 11 '08 at 6:55






            • 264




              @Lorenzo: No, in Java everything is passed by value. Primitives are passed by value, and object references are passed by value. The objects themselves are never passed to a method, but the objects are always in the heap and only a reference to the object is passed to the method.
              – Esko Luontola
              Feb 12 '09 at 23:02






            • 258




              My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed.
              – dhackner
              Oct 20 '10 at 16:38








            • 126




              What's confusing is that object references are actually pointers. In the beginning SUN called them pointers. Then marketing informed that "pointer" was a bad word. But you still see the "correct" nomenclature in NullPointerException.
              – Prof. Falken
              Feb 9 '11 at 9:46















            up vote
            4906
            down vote



            +50







            up vote
            4906
            down vote



            +50




            +50




            Java is always pass-by-value. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners.



            It goes like this:



            public static void main(String args) {
            Dog aDog = new Dog("Max");
            // we pass the object to foo
            foo(aDog);
            // aDog variable is still pointing to the "Max" dog when foo(...) returns
            aDog.getName().equals("Max"); // true
            aDog.getName().equals("Fifi"); // false
            }

            public static void foo(Dog d) {
            d.getName().equals("Max"); // true
            // change d inside of foo() to point to a new Dog instance "Fifi"
            d = new Dog("Fifi");
            d.getName().equals("Fifi"); // true
            }


            In the example above aDog.getName() will still return "Max". The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.



            Likewise:



            public static void main(String args) {
            Dog aDog = new Dog("Max");
            foo(aDog);
            // when foo(...) returns, the name of the dog has been changed to "Fifi"
            aDog.getName().equals("Fifi"); // true
            }

            public static void foo(Dog d) {
            d.getName().equals("Max"); // true
            // this changes the name of d to be "Fifi"
            d.setName("Fifi");
            }


            In the above example, Fifi is the dog's name after call to foo(aDog) because the object's name was set inside of foo(...). Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog itself (except when d is changed to point to a different Dog instance like d = new Dog("Boxer")).





            share














            Java is always pass-by-value. Unfortunately, they decided to call the location of an object a "reference". When we pass the value of an object, we are passing the reference to it. This is confusing to beginners.



            It goes like this:



            public static void main(String args) {
            Dog aDog = new Dog("Max");
            // we pass the object to foo
            foo(aDog);
            // aDog variable is still pointing to the "Max" dog when foo(...) returns
            aDog.getName().equals("Max"); // true
            aDog.getName().equals("Fifi"); // false
            }

            public static void foo(Dog d) {
            d.getName().equals("Max"); // true
            // change d inside of foo() to point to a new Dog instance "Fifi"
            d = new Dog("Fifi");
            d.getName().equals("Fifi"); // true
            }


            In the example above aDog.getName() will still return "Max". The value aDog within main is not changed in the function foo with the Dog "Fifi" as the object reference is passed by value. If it were passed by reference, then the aDog.getName() in main would return "Fifi" after the call to foo.



            Likewise:



            public static void main(String args) {
            Dog aDog = new Dog("Max");
            foo(aDog);
            // when foo(...) returns, the name of the dog has been changed to "Fifi"
            aDog.getName().equals("Fifi"); // true
            }

            public static void foo(Dog d) {
            d.getName().equals("Max"); // true
            // this changes the name of d to be "Fifi"
            d.setName("Fifi");
            }


            In the above example, Fifi is the dog's name after call to foo(aDog) because the object's name was set inside of foo(...). Any operations that foo performs on d are such that, for all practical purposes, they are performed on aDog itself (except when d is changed to point to a different Dog instance like d = new Dog("Boxer")).






            share













            share


            share








            edited Jun 30 at 22:53


























            community wiki





            27 revs, 25 users 35%
            erlando









            • 219




              Isn't it slightly confusing the issue with internal details? There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'.
              – izb
              Sep 8 '08 at 14:58






            • 336




              But there is a subtle difference. Look at the first example. If it was purely pass by reference, aDog.name would be "Fifi". It isn't - the reference you are getting is a value reference that if overwritten will be restored when exiting the function.
              – erlando
              Sep 11 '08 at 6:55






            • 264




              @Lorenzo: No, in Java everything is passed by value. Primitives are passed by value, and object references are passed by value. The objects themselves are never passed to a method, but the objects are always in the heap and only a reference to the object is passed to the method.
              – Esko Luontola
              Feb 12 '09 at 23:02






            • 258




              My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed.
              – dhackner
              Oct 20 '10 at 16:38








            • 126




              What's confusing is that object references are actually pointers. In the beginning SUN called them pointers. Then marketing informed that "pointer" was a bad word. But you still see the "correct" nomenclature in NullPointerException.
              – Prof. Falken
              Feb 9 '11 at 9:46
















            • 219




              Isn't it slightly confusing the issue with internal details? There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'.
              – izb
              Sep 8 '08 at 14:58






            • 336




              But there is a subtle difference. Look at the first example. If it was purely pass by reference, aDog.name would be "Fifi". It isn't - the reference you are getting is a value reference that if overwritten will be restored when exiting the function.
              – erlando
              Sep 11 '08 at 6:55






            • 264




              @Lorenzo: No, in Java everything is passed by value. Primitives are passed by value, and object references are passed by value. The objects themselves are never passed to a method, but the objects are always in the heap and only a reference to the object is passed to the method.
              – Esko Luontola
              Feb 12 '09 at 23:02






            • 258




              My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed.
              – dhackner
              Oct 20 '10 at 16:38








            • 126




              What's confusing is that object references are actually pointers. In the beginning SUN called them pointers. Then marketing informed that "pointer" was a bad word. But you still see the "correct" nomenclature in NullPointerException.
              – Prof. Falken
              Feb 9 '11 at 9:46










            219




            219




            Isn't it slightly confusing the issue with internal details? There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'.
            – izb
            Sep 8 '08 at 14:58




            Isn't it slightly confusing the issue with internal details? There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'.
            – izb
            Sep 8 '08 at 14:58




            336




            336




            But there is a subtle difference. Look at the first example. If it was purely pass by reference, aDog.name would be "Fifi". It isn't - the reference you are getting is a value reference that if overwritten will be restored when exiting the function.
            – erlando
            Sep 11 '08 at 6:55




            But there is a subtle difference. Look at the first example. If it was purely pass by reference, aDog.name would be "Fifi". It isn't - the reference you are getting is a value reference that if overwritten will be restored when exiting the function.
            – erlando
            Sep 11 '08 at 6:55




            264




            264




            @Lorenzo: No, in Java everything is passed by value. Primitives are passed by value, and object references are passed by value. The objects themselves are never passed to a method, but the objects are always in the heap and only a reference to the object is passed to the method.
            – Esko Luontola
            Feb 12 '09 at 23:02




            @Lorenzo: No, in Java everything is passed by value. Primitives are passed by value, and object references are passed by value. The objects themselves are never passed to a method, but the objects are always in the heap and only a reference to the object is passed to the method.
            – Esko Luontola
            Feb 12 '09 at 23:02




            258




            258




            My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed.
            – dhackner
            Oct 20 '10 at 16:38






            My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed.
            – dhackner
            Oct 20 '10 at 16:38






            126




            126




            What's confusing is that object references are actually pointers. In the beginning SUN called them pointers. Then marketing informed that "pointer" was a bad word. But you still see the "correct" nomenclature in NullPointerException.
            – Prof. Falken
            Feb 9 '11 at 9:46






            What's confusing is that object references are actually pointers. In the beginning SUN called them pointers. Then marketing informed that "pointer" was a bad word. But you still see the "correct" nomenclature in NullPointerException.
            – Prof. Falken
            Feb 9 '11 at 9:46














            up vote
            2704
            down vote













            I just noticed you referenced my article.



            The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.



            The key to understanding this is that something like



            Dog myDog;


            is not a Dog; it's actually a pointer to a Dog.



            What that means, is when you have



            Dog myDog = new Dog("Rover");
            foo(myDog);


            you're essentially passing the address of the created Dog object to the foo method.



            (I say essentially because Java pointers aren't direct addresses, but it's easiest to think of them that way)



            Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.



            if the Method were defined as



            public void foo(Dog someDog) {
            someDog.setName("Max"); // AAA
            someDog = new Dog("Fifi"); // BBB
            someDog.setName("Rowlf"); // CCC
            }


            let's look at what's happening.




            • the parameter someDog is set to the value 42

            • at line "AAA"



              • someDog is followed to the Dog it points to (the Dog object at address 42)

              • that Dog (the one at address 42) is asked to change his name to Max



            • at line "BBB"


              • a new Dog is created. Let's say he's at address 74

              • we assign the parameter someDog to 74



            • at line "CCC"


              • someDog is followed to the Dog it points to (the Dog object at address 74)

              • that Dog (the one at address 74) is asked to change his name to Rowlf



            • then, we return


            Now let's think about what happens outside the method:



            Did myDog change?



            There's the key.



            Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog (but note that because of line "AAA", its name is now "Max" - still the same Dog; myDog's value has not changed.)



            It's perfectly valid to follow an address and change what's at the end of it; that does not change the variable, however.



            Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, you cannot change where that pointer points.



            In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.



            If Java had pass-by-reference semantics, the foo method we defined above would have changed where myDog was pointing when it assigned someDog on line BBB.



            Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.





            share



















            • 120




              This is why the common refrain "Java doesn't have pointers" is so misleading.
              – Beska
              Apr 2 '09 at 17:52






            • 122




              You are wrong, imho. "Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog." myDog has value 42 but its name argument now contains "Max", rather than "Rover" on // AAA line.
              – Özgür
              Apr 6 '09 at 5:22






            • 167




              Think about it this way. Someone has the address of Ann Arbor, MI (my hometown, GO BLUE!) on a slip of paper called "annArborLocation". You copy it down on a piece of paper called "myDestination". You can drive to "myDestination" and plant a tree. You may have changed something about the city at that location, but it doesn't change the LAT/LON that was written on either paper. You can change the LAT/LON on "myDestination" but it doesn't change "annArborLocation". Does that help?
              – Scott Stanchfield
              Apr 23 '09 at 13:06






            • 34




              @Scott Stanchfield: I read your article about a year ago and it really helped clear things up for me. Thanks! May I humbly suggest a little addition: you should mention that there is actually a specific term that describes this form of "call by value where the value is a reference" that was invented by Barbara Liskov for describing the evaluation strategy of her CLU language in 1974, in order to avoid confusion such as the one your article addresses: call by sharing (sometimes called call by object-sharing or simply call by object), which pretty much perfectly describes the semantics.
              – Jörg W Mittag
              Sep 7 '10 at 22:12






            • 23




              @Gevorg - The C/C++ languages don't own the concept of a "pointer". There are other languages that use pointers but do not allow the same types of manipulation of pointers that C/C++ allow. Java has pointers; they're just protected against mischief.
              – Scott Stanchfield
              Dec 30 '11 at 18:30















            up vote
            2704
            down vote













            I just noticed you referenced my article.



            The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.



            The key to understanding this is that something like



            Dog myDog;


            is not a Dog; it's actually a pointer to a Dog.



            What that means, is when you have



            Dog myDog = new Dog("Rover");
            foo(myDog);


            you're essentially passing the address of the created Dog object to the foo method.



            (I say essentially because Java pointers aren't direct addresses, but it's easiest to think of them that way)



            Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.



            if the Method were defined as



            public void foo(Dog someDog) {
            someDog.setName("Max"); // AAA
            someDog = new Dog("Fifi"); // BBB
            someDog.setName("Rowlf"); // CCC
            }


            let's look at what's happening.




            • the parameter someDog is set to the value 42

            • at line "AAA"



              • someDog is followed to the Dog it points to (the Dog object at address 42)

              • that Dog (the one at address 42) is asked to change his name to Max



            • at line "BBB"


              • a new Dog is created. Let's say he's at address 74

              • we assign the parameter someDog to 74



            • at line "CCC"


              • someDog is followed to the Dog it points to (the Dog object at address 74)

              • that Dog (the one at address 74) is asked to change his name to Rowlf



            • then, we return


            Now let's think about what happens outside the method:



            Did myDog change?



            There's the key.



            Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog (but note that because of line "AAA", its name is now "Max" - still the same Dog; myDog's value has not changed.)



            It's perfectly valid to follow an address and change what's at the end of it; that does not change the variable, however.



            Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, you cannot change where that pointer points.



            In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.



            If Java had pass-by-reference semantics, the foo method we defined above would have changed where myDog was pointing when it assigned someDog on line BBB.



            Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.





            share



















            • 120




              This is why the common refrain "Java doesn't have pointers" is so misleading.
              – Beska
              Apr 2 '09 at 17:52






            • 122




              You are wrong, imho. "Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog." myDog has value 42 but its name argument now contains "Max", rather than "Rover" on // AAA line.
              – Özgür
              Apr 6 '09 at 5:22






            • 167




              Think about it this way. Someone has the address of Ann Arbor, MI (my hometown, GO BLUE!) on a slip of paper called "annArborLocation". You copy it down on a piece of paper called "myDestination". You can drive to "myDestination" and plant a tree. You may have changed something about the city at that location, but it doesn't change the LAT/LON that was written on either paper. You can change the LAT/LON on "myDestination" but it doesn't change "annArborLocation". Does that help?
              – Scott Stanchfield
              Apr 23 '09 at 13:06






            • 34




              @Scott Stanchfield: I read your article about a year ago and it really helped clear things up for me. Thanks! May I humbly suggest a little addition: you should mention that there is actually a specific term that describes this form of "call by value where the value is a reference" that was invented by Barbara Liskov for describing the evaluation strategy of her CLU language in 1974, in order to avoid confusion such as the one your article addresses: call by sharing (sometimes called call by object-sharing or simply call by object), which pretty much perfectly describes the semantics.
              – Jörg W Mittag
              Sep 7 '10 at 22:12






            • 23




              @Gevorg - The C/C++ languages don't own the concept of a "pointer". There are other languages that use pointers but do not allow the same types of manipulation of pointers that C/C++ allow. Java has pointers; they're just protected against mischief.
              – Scott Stanchfield
              Dec 30 '11 at 18:30













            up vote
            2704
            down vote










            up vote
            2704
            down vote









            I just noticed you referenced my article.



            The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.



            The key to understanding this is that something like



            Dog myDog;


            is not a Dog; it's actually a pointer to a Dog.



            What that means, is when you have



            Dog myDog = new Dog("Rover");
            foo(myDog);


            you're essentially passing the address of the created Dog object to the foo method.



            (I say essentially because Java pointers aren't direct addresses, but it's easiest to think of them that way)



            Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.



            if the Method were defined as



            public void foo(Dog someDog) {
            someDog.setName("Max"); // AAA
            someDog = new Dog("Fifi"); // BBB
            someDog.setName("Rowlf"); // CCC
            }


            let's look at what's happening.




            • the parameter someDog is set to the value 42

            • at line "AAA"



              • someDog is followed to the Dog it points to (the Dog object at address 42)

              • that Dog (the one at address 42) is asked to change his name to Max



            • at line "BBB"


              • a new Dog is created. Let's say he's at address 74

              • we assign the parameter someDog to 74



            • at line "CCC"


              • someDog is followed to the Dog it points to (the Dog object at address 74)

              • that Dog (the one at address 74) is asked to change his name to Rowlf



            • then, we return


            Now let's think about what happens outside the method:



            Did myDog change?



            There's the key.



            Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog (but note that because of line "AAA", its name is now "Max" - still the same Dog; myDog's value has not changed.)



            It's perfectly valid to follow an address and change what's at the end of it; that does not change the variable, however.



            Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, you cannot change where that pointer points.



            In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.



            If Java had pass-by-reference semantics, the foo method we defined above would have changed where myDog was pointing when it assigned someDog on line BBB.



            Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.





            share














            I just noticed you referenced my article.



            The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java.



            The key to understanding this is that something like



            Dog myDog;


            is not a Dog; it's actually a pointer to a Dog.



            What that means, is when you have



            Dog myDog = new Dog("Rover");
            foo(myDog);


            you're essentially passing the address of the created Dog object to the foo method.



            (I say essentially because Java pointers aren't direct addresses, but it's easiest to think of them that way)



            Suppose the Dog object resides at memory address 42. This means we pass 42 to the method.



            if the Method were defined as



            public void foo(Dog someDog) {
            someDog.setName("Max"); // AAA
            someDog = new Dog("Fifi"); // BBB
            someDog.setName("Rowlf"); // CCC
            }


            let's look at what's happening.




            • the parameter someDog is set to the value 42

            • at line "AAA"



              • someDog is followed to the Dog it points to (the Dog object at address 42)

              • that Dog (the one at address 42) is asked to change his name to Max



            • at line "BBB"


              • a new Dog is created. Let's say he's at address 74

              • we assign the parameter someDog to 74



            • at line "CCC"


              • someDog is followed to the Dog it points to (the Dog object at address 74)

              • that Dog (the one at address 74) is asked to change his name to Rowlf



            • then, we return


            Now let's think about what happens outside the method:



            Did myDog change?



            There's the key.



            Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog (but note that because of line "AAA", its name is now "Max" - still the same Dog; myDog's value has not changed.)



            It's perfectly valid to follow an address and change what's at the end of it; that does not change the variable, however.



            Java works exactly like C. You can assign a pointer, pass the pointer to a method, follow the pointer in the method and change the data that was pointed to. However, you cannot change where that pointer points.



            In C++, Ada, Pascal and other languages that support pass-by-reference, you can actually change the variable that was passed.



            If Java had pass-by-reference semantics, the foo method we defined above would have changed where myDog was pointing when it assigned someDog on line BBB.



            Think of reference parameters as being aliases for the variable passed in. When that alias is assigned, so is the variable that was passed in.






            share













            share


            share








            edited Aug 28 '15 at 15:32


























            community wiki





            11 revs, 6 users 73%
            Scott Stanchfield









            • 120




              This is why the common refrain "Java doesn't have pointers" is so misleading.
              – Beska
              Apr 2 '09 at 17:52






            • 122




              You are wrong, imho. "Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog." myDog has value 42 but its name argument now contains "Max", rather than "Rover" on // AAA line.
              – Özgür
              Apr 6 '09 at 5:22






            • 167




              Think about it this way. Someone has the address of Ann Arbor, MI (my hometown, GO BLUE!) on a slip of paper called "annArborLocation". You copy it down on a piece of paper called "myDestination". You can drive to "myDestination" and plant a tree. You may have changed something about the city at that location, but it doesn't change the LAT/LON that was written on either paper. You can change the LAT/LON on "myDestination" but it doesn't change "annArborLocation". Does that help?
              – Scott Stanchfield
              Apr 23 '09 at 13:06






            • 34




              @Scott Stanchfield: I read your article about a year ago and it really helped clear things up for me. Thanks! May I humbly suggest a little addition: you should mention that there is actually a specific term that describes this form of "call by value where the value is a reference" that was invented by Barbara Liskov for describing the evaluation strategy of her CLU language in 1974, in order to avoid confusion such as the one your article addresses: call by sharing (sometimes called call by object-sharing or simply call by object), which pretty much perfectly describes the semantics.
              – Jörg W Mittag
              Sep 7 '10 at 22:12






            • 23




              @Gevorg - The C/C++ languages don't own the concept of a "pointer". There are other languages that use pointers but do not allow the same types of manipulation of pointers that C/C++ allow. Java has pointers; they're just protected against mischief.
              – Scott Stanchfield
              Dec 30 '11 at 18:30














            • 120




              This is why the common refrain "Java doesn't have pointers" is so misleading.
              – Beska
              Apr 2 '09 at 17:52






            • 122




              You are wrong, imho. "Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog." myDog has value 42 but its name argument now contains "Max", rather than "Rover" on // AAA line.
              – Özgür
              Apr 6 '09 at 5:22






            • 167




              Think about it this way. Someone has the address of Ann Arbor, MI (my hometown, GO BLUE!) on a slip of paper called "annArborLocation". You copy it down on a piece of paper called "myDestination". You can drive to "myDestination" and plant a tree. You may have changed something about the city at that location, but it doesn't change the LAT/LON that was written on either paper. You can change the LAT/LON on "myDestination" but it doesn't change "annArborLocation". Does that help?
              – Scott Stanchfield
              Apr 23 '09 at 13:06






            • 34




              @Scott Stanchfield: I read your article about a year ago and it really helped clear things up for me. Thanks! May I humbly suggest a little addition: you should mention that there is actually a specific term that describes this form of "call by value where the value is a reference" that was invented by Barbara Liskov for describing the evaluation strategy of her CLU language in 1974, in order to avoid confusion such as the one your article addresses: call by sharing (sometimes called call by object-sharing or simply call by object), which pretty much perfectly describes the semantics.
              – Jörg W Mittag
              Sep 7 '10 at 22:12






            • 23




              @Gevorg - The C/C++ languages don't own the concept of a "pointer". There are other languages that use pointers but do not allow the same types of manipulation of pointers that C/C++ allow. Java has pointers; they're just protected against mischief.
              – Scott Stanchfield
              Dec 30 '11 at 18:30








            120




            120




            This is why the common refrain "Java doesn't have pointers" is so misleading.
            – Beska
            Apr 2 '09 at 17:52




            This is why the common refrain "Java doesn't have pointers" is so misleading.
            – Beska
            Apr 2 '09 at 17:52




            122




            122




            You are wrong, imho. "Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog." myDog has value 42 but its name argument now contains "Max", rather than "Rover" on // AAA line.
            – Özgür
            Apr 6 '09 at 5:22




            You are wrong, imho. "Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog." myDog has value 42 but its name argument now contains "Max", rather than "Rover" on // AAA line.
            – Özgür
            Apr 6 '09 at 5:22




            167




            167




            Think about it this way. Someone has the address of Ann Arbor, MI (my hometown, GO BLUE!) on a slip of paper called "annArborLocation". You copy it down on a piece of paper called "myDestination". You can drive to "myDestination" and plant a tree. You may have changed something about the city at that location, but it doesn't change the LAT/LON that was written on either paper. You can change the LAT/LON on "myDestination" but it doesn't change "annArborLocation". Does that help?
            – Scott Stanchfield
            Apr 23 '09 at 13:06




            Think about it this way. Someone has the address of Ann Arbor, MI (my hometown, GO BLUE!) on a slip of paper called "annArborLocation". You copy it down on a piece of paper called "myDestination". You can drive to "myDestination" and plant a tree. You may have changed something about the city at that location, but it doesn't change the LAT/LON that was written on either paper. You can change the LAT/LON on "myDestination" but it doesn't change "annArborLocation". Does that help?
            – Scott Stanchfield
            Apr 23 '09 at 13:06




            34




            34




            @Scott Stanchfield: I read your article about a year ago and it really helped clear things up for me. Thanks! May I humbly suggest a little addition: you should mention that there is actually a specific term that describes this form of "call by value where the value is a reference" that was invented by Barbara Liskov for describing the evaluation strategy of her CLU language in 1974, in order to avoid confusion such as the one your article addresses: call by sharing (sometimes called call by object-sharing or simply call by object), which pretty much perfectly describes the semantics.
            – Jörg W Mittag
            Sep 7 '10 at 22:12




            @Scott Stanchfield: I read your article about a year ago and it really helped clear things up for me. Thanks! May I humbly suggest a little addition: you should mention that there is actually a specific term that describes this form of "call by value where the value is a reference" that was invented by Barbara Liskov for describing the evaluation strategy of her CLU language in 1974, in order to avoid confusion such as the one your article addresses: call by sharing (sometimes called call by object-sharing or simply call by object), which pretty much perfectly describes the semantics.
            – Jörg W Mittag
            Sep 7 '10 at 22:12




            23




            23




            @Gevorg - The C/C++ languages don't own the concept of a "pointer". There are other languages that use pointers but do not allow the same types of manipulation of pointers that C/C++ allow. Java has pointers; they're just protected against mischief.
            – Scott Stanchfield
            Dec 30 '11 at 18:30




            @Gevorg - The C/C++ languages don't own the concept of a "pointer". There are other languages that use pointers but do not allow the same types of manipulation of pointers that C/C++ allow. Java has pointers; they're just protected against mischief.
            – Scott Stanchfield
            Dec 30 '11 at 18:30










            up vote
            1429
            down vote













            Java always passes arguments by value NOT by reference.





            Let me explain this through an example:



            public class Main{
            public static void main(String args){
            Foo f = new Foo("f");
            changeReference(f); // It won't change the reference!
            modifyReference(f); // It will modify the object that the reference variable "f" refers to!
            }
            public static void changeReference(Foo a){
            Foo b = new Foo("b");
            a = b;
            }
            public static void modifyReference(Foo c){
            c.setAttribute("c");
            }
            }


            I will explain this in steps:





            1. Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".



              Foo f = new Foo("f");


              enter image description here




            2. From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.



              public static void changeReference(Foo a)


              enter image description here




            3. As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.



              changeReference(f);


              enter image description here




            4. Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".



              Foo b = new Foo("b");


              enter image description here




            5. a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".



              enter image description here







            6. As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".



              enter image description here




            7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's same object that reference f points to it.



              enter image description here




            I hope you understand now how passing objects as arguments works in Java :)





            share



















            • 57




              +1 Nice stuff. good diagrams. I also found a nice succinct page here adp-gmbh.ch/php/pass_by_reference.html OK I admit it is written in PHP, but it is the priciple of understanding the difference that I think is important (and how to manipulate that difference to your needs).
              – DaveM
              Jun 7 '13 at 8:46






            • 3




              @Eng.Fouad It's a nice explanation but if a points to the same object as f (and never gets its own copy of the object f points to), any changes to the object made using a should modify f aswell (since they are both working with the same object), so at some point a must get its own copy of the object f points to.
              – Mr D
              Jul 15 '13 at 19:08






            • 10




              @MrD when 'a' points to the same object 'f' also points to, then any change made to that object via 'a' is also observable via 'f', BUT IT DID NOT CHANGE 'f'. 'f' still points to the same object. You can totally change the object, but you can never change what 'f' points to. This is the fundamental issue that for some reason some people just can't comprehend.
              – Mike Braun
              Dec 1 '13 at 13:02










            • @MikeBraun ...what? Now you've confused me :S. Isn't what you just wrote contrary to what 6. and 7. shows?
              – Evil Washing Machine
              Nov 18 '14 at 11:34






            • 4




              This is the best explanation I've found. By the way, what about the basic situation? For example, the argument requires an int type, does it still pass the copy of an int variable to the argument?
              – allenwang
              May 21 '16 at 12:38















            up vote
            1429
            down vote













            Java always passes arguments by value NOT by reference.





            Let me explain this through an example:



            public class Main{
            public static void main(String args){
            Foo f = new Foo("f");
            changeReference(f); // It won't change the reference!
            modifyReference(f); // It will modify the object that the reference variable "f" refers to!
            }
            public static void changeReference(Foo a){
            Foo b = new Foo("b");
            a = b;
            }
            public static void modifyReference(Foo c){
            c.setAttribute("c");
            }
            }


            I will explain this in steps:





            1. Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".



              Foo f = new Foo("f");


              enter image description here




            2. From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.



              public static void changeReference(Foo a)


              enter image description here




            3. As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.



              changeReference(f);


              enter image description here




            4. Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".



              Foo b = new Foo("b");


              enter image description here




            5. a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".



              enter image description here







            6. As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".



              enter image description here




            7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's same object that reference f points to it.



              enter image description here




            I hope you understand now how passing objects as arguments works in Java :)





            share



















            • 57




              +1 Nice stuff. good diagrams. I also found a nice succinct page here adp-gmbh.ch/php/pass_by_reference.html OK I admit it is written in PHP, but it is the priciple of understanding the difference that I think is important (and how to manipulate that difference to your needs).
              – DaveM
              Jun 7 '13 at 8:46






            • 3




              @Eng.Fouad It's a nice explanation but if a points to the same object as f (and never gets its own copy of the object f points to), any changes to the object made using a should modify f aswell (since they are both working with the same object), so at some point a must get its own copy of the object f points to.
              – Mr D
              Jul 15 '13 at 19:08






            • 10




              @MrD when 'a' points to the same object 'f' also points to, then any change made to that object via 'a' is also observable via 'f', BUT IT DID NOT CHANGE 'f'. 'f' still points to the same object. You can totally change the object, but you can never change what 'f' points to. This is the fundamental issue that for some reason some people just can't comprehend.
              – Mike Braun
              Dec 1 '13 at 13:02










            • @MikeBraun ...what? Now you've confused me :S. Isn't what you just wrote contrary to what 6. and 7. shows?
              – Evil Washing Machine
              Nov 18 '14 at 11:34






            • 4




              This is the best explanation I've found. By the way, what about the basic situation? For example, the argument requires an int type, does it still pass the copy of an int variable to the argument?
              – allenwang
              May 21 '16 at 12:38













            up vote
            1429
            down vote










            up vote
            1429
            down vote









            Java always passes arguments by value NOT by reference.





            Let me explain this through an example:



            public class Main{
            public static void main(String args){
            Foo f = new Foo("f");
            changeReference(f); // It won't change the reference!
            modifyReference(f); // It will modify the object that the reference variable "f" refers to!
            }
            public static void changeReference(Foo a){
            Foo b = new Foo("b");
            a = b;
            }
            public static void modifyReference(Foo c){
            c.setAttribute("c");
            }
            }


            I will explain this in steps:





            1. Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".



              Foo f = new Foo("f");


              enter image description here




            2. From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.



              public static void changeReference(Foo a)


              enter image description here




            3. As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.



              changeReference(f);


              enter image description here




            4. Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".



              Foo b = new Foo("b");


              enter image description here




            5. a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".



              enter image description here







            6. As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".



              enter image description here




            7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's same object that reference f points to it.



              enter image description here




            I hope you understand now how passing objects as arguments works in Java :)





            share














            Java always passes arguments by value NOT by reference.





            Let me explain this through an example:



            public class Main{
            public static void main(String args){
            Foo f = new Foo("f");
            changeReference(f); // It won't change the reference!
            modifyReference(f); // It will modify the object that the reference variable "f" refers to!
            }
            public static void changeReference(Foo a){
            Foo b = new Foo("b");
            a = b;
            }
            public static void modifyReference(Foo c){
            c.setAttribute("c");
            }
            }


            I will explain this in steps:





            1. Declaring a reference named f of type Foo and assign it to a new object of type Foo with an attribute "f".



              Foo f = new Foo("f");


              enter image description here




            2. From the method side, a reference of type Foo with a name a is declared and it's initially assigned to null.



              public static void changeReference(Foo a)


              enter image description here




            3. As you call the method changeReference, the reference a will be assigned to the object which is passed as an argument.



              changeReference(f);


              enter image description here




            4. Declaring a reference named b of type Foo and assign it to a new object of type Foo with an attribute "b".



              Foo b = new Foo("b");


              enter image description here




            5. a = b is re-assigning the reference a NOT f to the object whose its attribute is "b".



              enter image description here







            6. As you call modifyReference(Foo c) method, a reference c is created and assigned to the object with attribute "f".



              enter image description here




            7. c.setAttribute("c"); will change the attribute of the object that reference c points to it, and it's same object that reference f points to it.



              enter image description here




            I hope you understand now how passing objects as arguments works in Java :)






            share













            share


            share








            edited May 23 '17 at 10:31


























            community wiki





            4 revs, 3 users 88%
            Eng.Fouad









            • 57




              +1 Nice stuff. good diagrams. I also found a nice succinct page here adp-gmbh.ch/php/pass_by_reference.html OK I admit it is written in PHP, but it is the priciple of understanding the difference that I think is important (and how to manipulate that difference to your needs).
              – DaveM
              Jun 7 '13 at 8:46






            • 3




              @Eng.Fouad It's a nice explanation but if a points to the same object as f (and never gets its own copy of the object f points to), any changes to the object made using a should modify f aswell (since they are both working with the same object), so at some point a must get its own copy of the object f points to.
              – Mr D
              Jul 15 '13 at 19:08






            • 10




              @MrD when 'a' points to the same object 'f' also points to, then any change made to that object via 'a' is also observable via 'f', BUT IT DID NOT CHANGE 'f'. 'f' still points to the same object. You can totally change the object, but you can never change what 'f' points to. This is the fundamental issue that for some reason some people just can't comprehend.
              – Mike Braun
              Dec 1 '13 at 13:02










            • @MikeBraun ...what? Now you've confused me :S. Isn't what you just wrote contrary to what 6. and 7. shows?
              – Evil Washing Machine
              Nov 18 '14 at 11:34






            • 4




              This is the best explanation I've found. By the way, what about the basic situation? For example, the argument requires an int type, does it still pass the copy of an int variable to the argument?
              – allenwang
              May 21 '16 at 12:38














            • 57




              +1 Nice stuff. good diagrams. I also found a nice succinct page here adp-gmbh.ch/php/pass_by_reference.html OK I admit it is written in PHP, but it is the priciple of understanding the difference that I think is important (and how to manipulate that difference to your needs).
              – DaveM
              Jun 7 '13 at 8:46






            • 3




              @Eng.Fouad It's a nice explanation but if a points to the same object as f (and never gets its own copy of the object f points to), any changes to the object made using a should modify f aswell (since they are both working with the same object), so at some point a must get its own copy of the object f points to.
              – Mr D
              Jul 15 '13 at 19:08






            • 10




              @MrD when 'a' points to the same object 'f' also points to, then any change made to that object via 'a' is also observable via 'f', BUT IT DID NOT CHANGE 'f'. 'f' still points to the same object. You can totally change the object, but you can never change what 'f' points to. This is the fundamental issue that for some reason some people just can't comprehend.
              – Mike Braun
              Dec 1 '13 at 13:02










            • @MikeBraun ...what? Now you've confused me :S. Isn't what you just wrote contrary to what 6. and 7. shows?
              – Evil Washing Machine
              Nov 18 '14 at 11:34






            • 4




              This is the best explanation I've found. By the way, what about the basic situation? For example, the argument requires an int type, does it still pass the copy of an int variable to the argument?
              – allenwang
              May 21 '16 at 12:38








            57




            57




            +1 Nice stuff. good diagrams. I also found a nice succinct page here adp-gmbh.ch/php/pass_by_reference.html OK I admit it is written in PHP, but it is the priciple of understanding the difference that I think is important (and how to manipulate that difference to your needs).
            – DaveM
            Jun 7 '13 at 8:46




            +1 Nice stuff. good diagrams. I also found a nice succinct page here adp-gmbh.ch/php/pass_by_reference.html OK I admit it is written in PHP, but it is the priciple of understanding the difference that I think is important (and how to manipulate that difference to your needs).
            – DaveM
            Jun 7 '13 at 8:46




            3




            3




            @Eng.Fouad It's a nice explanation but if a points to the same object as f (and never gets its own copy of the object f points to), any changes to the object made using a should modify f aswell (since they are both working with the same object), so at some point a must get its own copy of the object f points to.
            – Mr D
            Jul 15 '13 at 19:08




            @Eng.Fouad It's a nice explanation but if a points to the same object as f (and never gets its own copy of the object f points to), any changes to the object made using a should modify f aswell (since they are both working with the same object), so at some point a must get its own copy of the object f points to.
            – Mr D
            Jul 15 '13 at 19:08




            10




            10




            @MrD when 'a' points to the same object 'f' also points to, then any change made to that object via 'a' is also observable via 'f', BUT IT DID NOT CHANGE 'f'. 'f' still points to the same object. You can totally change the object, but you can never change what 'f' points to. This is the fundamental issue that for some reason some people just can't comprehend.
            – Mike Braun
            Dec 1 '13 at 13:02




            @MrD when 'a' points to the same object 'f' also points to, then any change made to that object via 'a' is also observable via 'f', BUT IT DID NOT CHANGE 'f'. 'f' still points to the same object. You can totally change the object, but you can never change what 'f' points to. This is the fundamental issue that for some reason some people just can't comprehend.
            – Mike Braun
            Dec 1 '13 at 13:02












            @MikeBraun ...what? Now you've confused me :S. Isn't what you just wrote contrary to what 6. and 7. shows?
            – Evil Washing Machine
            Nov 18 '14 at 11:34




            @MikeBraun ...what? Now you've confused me :S. Isn't what you just wrote contrary to what 6. and 7. shows?
            – Evil Washing Machine
            Nov 18 '14 at 11:34




            4




            4




            This is the best explanation I've found. By the way, what about the basic situation? For example, the argument requires an int type, does it still pass the copy of an int variable to the argument?
            – allenwang
            May 21 '16 at 12:38




            This is the best explanation I've found. By the way, what about the basic situation? For example, the argument requires an int type, does it still pass the copy of an int variable to the argument?
            – allenwang
            May 21 '16 at 12:38










            up vote
            671
            down vote













            This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you'll just smile :-)



            Step one please erase from your mind that word that starts with 'p' "_ _ _ _ _ _ _", especially if you come from other programming languages. Java and 'p' cannot be written in the same book, forum, or even txt.



            Step two remember that when you pass an Object into a method you're passing the Object reference and not the Object itself.





            • Student: Master, does this mean that Java is pass-by-reference?


            • Master: Grasshopper, No.


            Now think of what an Object's reference/variable does/is:




            1. A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).

            2. When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.

            3. So you're just passing 3bad086a that it's the value of the reference.

            4. You're passing the value of the reference and not the reference itself (and not the object).


            5. This value is actually COPIED and given to the method.


            In the following (please don't try to compile/execute this...):



            1. Person person;
            2. person = new Person("Tom");
            3. changeName(person);
            4.
            5. //I didn't use Person person below as an argument to be nice
            6. static void changeName(Person anotherReferenceToTheSamePersonObject) {
            7. anotherReferenceToTheSamePersonObject.setName("Jerry");
            8. }


            What happens?




            • The variable person is created in line #1 and it's null at the beginning.

            • A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is, its address. Let's say 3bad086a.

            • The variable person holding the address of the Object is passed to the function in line #3.

            • In line #4 you can listen to the sound of silence

            • Check the comment on line #5

            • A method local variable -anotherReferenceToTheSamePersonObject- is created and then comes the magic in line #6:


              • The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.

              • No new instances of Person are created.

              • Both "person" and "anotherReferenceToTheSamePersonObject" hold the same value of 3bad086a.

              • Don't try this but person==anotherReferenceToTheSamePersonObject would be true.

              • Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.




            A picture is worth a thousand words:



            Pass by Value



            Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!



            If you didn't get it then just trust me and remember that it's better to say that Java is pass by value. Well, pass by reference value. Oh well, even better is pass-by-copy-of-the-variable-value! ;)



            Now feel free to hate me but note that given this there is no difference between passing primitive data types and Objects when talking about method arguments.



            You always pass a copy of the bits of the value of the reference!




            • If it's a primitive data type these bits will contain the value of the primitive data type itself.

            • If it's an Object the bits will contain the value of the address that tells the JVM how to get to the Object.



            Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you'll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!







            The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.






            Of course you can cut it short and just say that Java is pass-by-value!





            share



















            • 5




              Do you mean pointers?.. If I get it correctly, in public void foo(Car car){ ... }, car is local to foo and it contains the heap location of the Object? So if I change car's value by car = new Car(), it will point to different Object on the heap? and if I change car's property valu by car.Color = "Red", the Object in the heap pointed by car will be modified. Also, it is the same in C#? Please reply! Thanks!
              – dpp
              Feb 25 '12 at 3:29






            • 9




              @domanokz You're killing me, please don't say that word again! ;) Note that I could have answered this question without saying 'reference' as well. It's a terminology issue and 'p's make it worse. Me and Scot have different views on this unfortunately. I think you got how it works in Java, now you can call it pass by-value, by-object-sharing, by-copy-of-the-variable-value, or feel free to come up with something else! I don't really care as long as you got how it works and what's in a variable of type Object: just a PO Box address! ;)
              – Gevorg
              Feb 25 '12 at 21:25






            • 8




              Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
              – John Strickler
              Mar 12 '14 at 17:38






            • 3




              I guess Java designed with pointers in mind. Otherwise, why NullPointerException exists? Nevertheless, for this wonderful explanantion, getting pointers will just make it complicated
              – brain storm
              Aug 20 '14 at 17:42






            • 3




              So drop in on theoretical line #9 System.out.println(person.getName()); what will show up? "Tom" or "Jerry"? This is the last thing that will help me hurdle this confusion.
              – TheBrenny
              Oct 19 '14 at 12:20















            up vote
            671
            down vote













            This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you'll just smile :-)



            Step one please erase from your mind that word that starts with 'p' "_ _ _ _ _ _ _", especially if you come from other programming languages. Java and 'p' cannot be written in the same book, forum, or even txt.



            Step two remember that when you pass an Object into a method you're passing the Object reference and not the Object itself.





            • Student: Master, does this mean that Java is pass-by-reference?


            • Master: Grasshopper, No.


            Now think of what an Object's reference/variable does/is:




            1. A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).

            2. When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.

            3. So you're just passing 3bad086a that it's the value of the reference.

            4. You're passing the value of the reference and not the reference itself (and not the object).


            5. This value is actually COPIED and given to the method.


            In the following (please don't try to compile/execute this...):



            1. Person person;
            2. person = new Person("Tom");
            3. changeName(person);
            4.
            5. //I didn't use Person person below as an argument to be nice
            6. static void changeName(Person anotherReferenceToTheSamePersonObject) {
            7. anotherReferenceToTheSamePersonObject.setName("Jerry");
            8. }


            What happens?




            • The variable person is created in line #1 and it's null at the beginning.

            • A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is, its address. Let's say 3bad086a.

            • The variable person holding the address of the Object is passed to the function in line #3.

            • In line #4 you can listen to the sound of silence

            • Check the comment on line #5

            • A method local variable -anotherReferenceToTheSamePersonObject- is created and then comes the magic in line #6:


              • The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.

              • No new instances of Person are created.

              • Both "person" and "anotherReferenceToTheSamePersonObject" hold the same value of 3bad086a.

              • Don't try this but person==anotherReferenceToTheSamePersonObject would be true.

              • Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.




            A picture is worth a thousand words:



            Pass by Value



            Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!



            If you didn't get it then just trust me and remember that it's better to say that Java is pass by value. Well, pass by reference value. Oh well, even better is pass-by-copy-of-the-variable-value! ;)



            Now feel free to hate me but note that given this there is no difference between passing primitive data types and Objects when talking about method arguments.



            You always pass a copy of the bits of the value of the reference!




            • If it's a primitive data type these bits will contain the value of the primitive data type itself.

            • If it's an Object the bits will contain the value of the address that tells the JVM how to get to the Object.



            Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you'll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!







            The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.






            Of course you can cut it short and just say that Java is pass-by-value!





            share



















            • 5




              Do you mean pointers?.. If I get it correctly, in public void foo(Car car){ ... }, car is local to foo and it contains the heap location of the Object? So if I change car's value by car = new Car(), it will point to different Object on the heap? and if I change car's property valu by car.Color = "Red", the Object in the heap pointed by car will be modified. Also, it is the same in C#? Please reply! Thanks!
              – dpp
              Feb 25 '12 at 3:29






            • 9




              @domanokz You're killing me, please don't say that word again! ;) Note that I could have answered this question without saying 'reference' as well. It's a terminology issue and 'p's make it worse. Me and Scot have different views on this unfortunately. I think you got how it works in Java, now you can call it pass by-value, by-object-sharing, by-copy-of-the-variable-value, or feel free to come up with something else! I don't really care as long as you got how it works and what's in a variable of type Object: just a PO Box address! ;)
              – Gevorg
              Feb 25 '12 at 21:25






            • 8




              Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
              – John Strickler
              Mar 12 '14 at 17:38






            • 3




              I guess Java designed with pointers in mind. Otherwise, why NullPointerException exists? Nevertheless, for this wonderful explanantion, getting pointers will just make it complicated
              – brain storm
              Aug 20 '14 at 17:42






            • 3




              So drop in on theoretical line #9 System.out.println(person.getName()); what will show up? "Tom" or "Jerry"? This is the last thing that will help me hurdle this confusion.
              – TheBrenny
              Oct 19 '14 at 12:20













            up vote
            671
            down vote










            up vote
            671
            down vote









            This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you'll just smile :-)



            Step one please erase from your mind that word that starts with 'p' "_ _ _ _ _ _ _", especially if you come from other programming languages. Java and 'p' cannot be written in the same book, forum, or even txt.



            Step two remember that when you pass an Object into a method you're passing the Object reference and not the Object itself.





            • Student: Master, does this mean that Java is pass-by-reference?


            • Master: Grasshopper, No.


            Now think of what an Object's reference/variable does/is:




            1. A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).

            2. When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.

            3. So you're just passing 3bad086a that it's the value of the reference.

            4. You're passing the value of the reference and not the reference itself (and not the object).


            5. This value is actually COPIED and given to the method.


            In the following (please don't try to compile/execute this...):



            1. Person person;
            2. person = new Person("Tom");
            3. changeName(person);
            4.
            5. //I didn't use Person person below as an argument to be nice
            6. static void changeName(Person anotherReferenceToTheSamePersonObject) {
            7. anotherReferenceToTheSamePersonObject.setName("Jerry");
            8. }


            What happens?




            • The variable person is created in line #1 and it's null at the beginning.

            • A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is, its address. Let's say 3bad086a.

            • The variable person holding the address of the Object is passed to the function in line #3.

            • In line #4 you can listen to the sound of silence

            • Check the comment on line #5

            • A method local variable -anotherReferenceToTheSamePersonObject- is created and then comes the magic in line #6:


              • The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.

              • No new instances of Person are created.

              • Both "person" and "anotherReferenceToTheSamePersonObject" hold the same value of 3bad086a.

              • Don't try this but person==anotherReferenceToTheSamePersonObject would be true.

              • Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.




            A picture is worth a thousand words:



            Pass by Value



            Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!



            If you didn't get it then just trust me and remember that it's better to say that Java is pass by value. Well, pass by reference value. Oh well, even better is pass-by-copy-of-the-variable-value! ;)



            Now feel free to hate me but note that given this there is no difference between passing primitive data types and Objects when talking about method arguments.



            You always pass a copy of the bits of the value of the reference!




            • If it's a primitive data type these bits will contain the value of the primitive data type itself.

            • If it's an Object the bits will contain the value of the address that tells the JVM how to get to the Object.



            Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you'll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!







            The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.






            Of course you can cut it short and just say that Java is pass-by-value!





            share














            This will give you some insights of how Java really works to the point that in your next discussion about Java passing by reference or passing by value you'll just smile :-)



            Step one please erase from your mind that word that starts with 'p' "_ _ _ _ _ _ _", especially if you come from other programming languages. Java and 'p' cannot be written in the same book, forum, or even txt.



            Step two remember that when you pass an Object into a method you're passing the Object reference and not the Object itself.





            • Student: Master, does this mean that Java is pass-by-reference?


            • Master: Grasshopper, No.


            Now think of what an Object's reference/variable does/is:




            1. A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).

            2. When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.

            3. So you're just passing 3bad086a that it's the value of the reference.

            4. You're passing the value of the reference and not the reference itself (and not the object).


            5. This value is actually COPIED and given to the method.


            In the following (please don't try to compile/execute this...):



            1. Person person;
            2. person = new Person("Tom");
            3. changeName(person);
            4.
            5. //I didn't use Person person below as an argument to be nice
            6. static void changeName(Person anotherReferenceToTheSamePersonObject) {
            7. anotherReferenceToTheSamePersonObject.setName("Jerry");
            8. }


            What happens?




            • The variable person is created in line #1 and it's null at the beginning.

            • A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is, its address. Let's say 3bad086a.

            • The variable person holding the address of the Object is passed to the function in line #3.

            • In line #4 you can listen to the sound of silence

            • Check the comment on line #5

            • A method local variable -anotherReferenceToTheSamePersonObject- is created and then comes the magic in line #6:


              • The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.

              • No new instances of Person are created.

              • Both "person" and "anotherReferenceToTheSamePersonObject" hold the same value of 3bad086a.

              • Don't try this but person==anotherReferenceToTheSamePersonObject would be true.

              • Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.




            A picture is worth a thousand words:



            Pass by Value



            Note that the anotherReferenceToTheSamePersonObject arrows is directed towards the Object and not towards the variable person!



            If you didn't get it then just trust me and remember that it's better to say that Java is pass by value. Well, pass by reference value. Oh well, even better is pass-by-copy-of-the-variable-value! ;)



            Now feel free to hate me but note that given this there is no difference between passing primitive data types and Objects when talking about method arguments.



            You always pass a copy of the bits of the value of the reference!




            • If it's a primitive data type these bits will contain the value of the primitive data type itself.

            • If it's an Object the bits will contain the value of the address that tells the JVM how to get to the Object.



            Java is pass-by-value because inside a method you can modify the referenced Object as much as you want but no matter how hard you try you'll never be able to modify the passed variable that will keep referencing (not p _ _ _ _ _ _ _) the same Object no matter what!







            The changeName function above will never be able to modify the actual content (the bit values) of the passed reference. In other word changeName cannot make Person person refer to another Object.






            Of course you can cut it short and just say that Java is pass-by-value!






            share













            share


            share








            edited Jan 4 at 10:17


























            community wiki





            3 revs, 2 users 95%
            Gevorg









            • 5




              Do you mean pointers?.. If I get it correctly, in public void foo(Car car){ ... }, car is local to foo and it contains the heap location of the Object? So if I change car's value by car = new Car(), it will point to different Object on the heap? and if I change car's property valu by car.Color = "Red", the Object in the heap pointed by car will be modified. Also, it is the same in C#? Please reply! Thanks!
              – dpp
              Feb 25 '12 at 3:29






            • 9




              @domanokz You're killing me, please don't say that word again! ;) Note that I could have answered this question without saying 'reference' as well. It's a terminology issue and 'p's make it worse. Me and Scot have different views on this unfortunately. I think you got how it works in Java, now you can call it pass by-value, by-object-sharing, by-copy-of-the-variable-value, or feel free to come up with something else! I don't really care as long as you got how it works and what's in a variable of type Object: just a PO Box address! ;)
              – Gevorg
              Feb 25 '12 at 21:25






            • 8




              Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
              – John Strickler
              Mar 12 '14 at 17:38






            • 3




              I guess Java designed with pointers in mind. Otherwise, why NullPointerException exists? Nevertheless, for this wonderful explanantion, getting pointers will just make it complicated
              – brain storm
              Aug 20 '14 at 17:42






            • 3




              So drop in on theoretical line #9 System.out.println(person.getName()); what will show up? "Tom" or "Jerry"? This is the last thing that will help me hurdle this confusion.
              – TheBrenny
              Oct 19 '14 at 12:20














            • 5




              Do you mean pointers?.. If I get it correctly, in public void foo(Car car){ ... }, car is local to foo and it contains the heap location of the Object? So if I change car's value by car = new Car(), it will point to different Object on the heap? and if I change car's property valu by car.Color = "Red", the Object in the heap pointed by car will be modified. Also, it is the same in C#? Please reply! Thanks!
              – dpp
              Feb 25 '12 at 3:29






            • 9




              @domanokz You're killing me, please don't say that word again! ;) Note that I could have answered this question without saying 'reference' as well. It's a terminology issue and 'p's make it worse. Me and Scot have different views on this unfortunately. I think you got how it works in Java, now you can call it pass by-value, by-object-sharing, by-copy-of-the-variable-value, or feel free to come up with something else! I don't really care as long as you got how it works and what's in a variable of type Object: just a PO Box address! ;)
              – Gevorg
              Feb 25 '12 at 21:25






            • 8




              Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
              – John Strickler
              Mar 12 '14 at 17:38






            • 3




              I guess Java designed with pointers in mind. Otherwise, why NullPointerException exists? Nevertheless, for this wonderful explanantion, getting pointers will just make it complicated
              – brain storm
              Aug 20 '14 at 17:42






            • 3




              So drop in on theoretical line #9 System.out.println(person.getName()); what will show up? "Tom" or "Jerry"? This is the last thing that will help me hurdle this confusion.
              – TheBrenny
              Oct 19 '14 at 12:20








            5




            5




            Do you mean pointers?.. If I get it correctly, in public void foo(Car car){ ... }, car is local to foo and it contains the heap location of the Object? So if I change car's value by car = new Car(), it will point to different Object on the heap? and if I change car's property valu by car.Color = "Red", the Object in the heap pointed by car will be modified. Also, it is the same in C#? Please reply! Thanks!
            – dpp
            Feb 25 '12 at 3:29




            Do you mean pointers?.. If I get it correctly, in public void foo(Car car){ ... }, car is local to foo and it contains the heap location of the Object? So if I change car's value by car = new Car(), it will point to different Object on the heap? and if I change car's property valu by car.Color = "Red", the Object in the heap pointed by car will be modified. Also, it is the same in C#? Please reply! Thanks!
            – dpp
            Feb 25 '12 at 3:29




            9




            9




            @domanokz You're killing me, please don't say that word again! ;) Note that I could have answered this question without saying 'reference' as well. It's a terminology issue and 'p's make it worse. Me and Scot have different views on this unfortunately. I think you got how it works in Java, now you can call it pass by-value, by-object-sharing, by-copy-of-the-variable-value, or feel free to come up with something else! I don't really care as long as you got how it works and what's in a variable of type Object: just a PO Box address! ;)
            – Gevorg
            Feb 25 '12 at 21:25




            @domanokz You're killing me, please don't say that word again! ;) Note that I could have answered this question without saying 'reference' as well. It's a terminology issue and 'p's make it worse. Me and Scot have different views on this unfortunately. I think you got how it works in Java, now you can call it pass by-value, by-object-sharing, by-copy-of-the-variable-value, or feel free to come up with something else! I don't really care as long as you got how it works and what's in a variable of type Object: just a PO Box address! ;)
            – Gevorg
            Feb 25 '12 at 21:25




            8




            8




            Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
            – John Strickler
            Mar 12 '14 at 17:38




            Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
            – John Strickler
            Mar 12 '14 at 17:38




            3




            3




            I guess Java designed with pointers in mind. Otherwise, why NullPointerException exists? Nevertheless, for this wonderful explanantion, getting pointers will just make it complicated
            – brain storm
            Aug 20 '14 at 17:42




            I guess Java designed with pointers in mind. Otherwise, why NullPointerException exists? Nevertheless, for this wonderful explanantion, getting pointers will just make it complicated
            – brain storm
            Aug 20 '14 at 17:42




            3




            3




            So drop in on theoretical line #9 System.out.println(person.getName()); what will show up? "Tom" or "Jerry"? This is the last thing that will help me hurdle this confusion.
            – TheBrenny
            Oct 19 '14 at 12:20




            So drop in on theoretical line #9 System.out.println(person.getName()); what will show up? "Tom" or "Jerry"? This is the last thing that will help me hurdle this confusion.
            – TheBrenny
            Oct 19 '14 at 12:20










            up vote
            582
            down vote













            Java is always pass by value, with no exceptions, ever.



            So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java never provides direct access to the values of objects themselves, in any circumstances. The only access to objects is through a reference to that object. Because Java objects are always accessed through a reference, rather than directly, it is common to talk about fields and variables and method arguments as being objects, when pedantically they are only references to objects. The confusion stems from this (strictly speaking, incorrect) change in nomenclature.



            So, when calling a method




            • For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive (for example, 3).

            • For objects, the pass by value is the value of the reference to the object.


            So if you have doSomething(foo) and public void doSomething(Foo foo) { .. } the two Foos have copied references that point to the same objects.



            Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.





            share



















            • 7




              Since the values of the primitives are immutable (like String), the difference between the two cases is not really relevant.
              – Paŭlo Ebermann
              Feb 3 '11 at 1:23






            • 4




              Exactly. For all you can tell via observable JVM behavior, primitives could be being passed by reference and could live on the heap. They don't, but that's not actually observable in any way.
              – Gravity
              Jul 31 '11 at 4:50






            • 5




              primitives are immutable? is that new in Java 7?
              – Carlos Heuberger
              Aug 22 '11 at 11:26






            • 2




              @CarlosHeuberger, "primitives are immutable?". The point is that you can pretend that 'primitives' are actually (mutable) references to immutable objects.
              – Aaron McDaid
              Jul 30 '15 at 16:29






            • 4




              Pointers are immutable, primitives in general are mutable. String is also not a primitive, it is an object. Moreover, the underlying structure of the String is a mutable array. The only immutable thing about it is the length, that being the inherent nature of arrays.
              – kingfrito_5005
              Aug 12 '15 at 18:44















            up vote
            582
            down vote













            Java is always pass by value, with no exceptions, ever.



            So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java never provides direct access to the values of objects themselves, in any circumstances. The only access to objects is through a reference to that object. Because Java objects are always accessed through a reference, rather than directly, it is common to talk about fields and variables and method arguments as being objects, when pedantically they are only references to objects. The confusion stems from this (strictly speaking, incorrect) change in nomenclature.



            So, when calling a method




            • For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive (for example, 3).

            • For objects, the pass by value is the value of the reference to the object.


            So if you have doSomething(foo) and public void doSomething(Foo foo) { .. } the two Foos have copied references that point to the same objects.



            Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.





            share



















            • 7




              Since the values of the primitives are immutable (like String), the difference between the two cases is not really relevant.
              – Paŭlo Ebermann
              Feb 3 '11 at 1:23






            • 4




              Exactly. For all you can tell via observable JVM behavior, primitives could be being passed by reference and could live on the heap. They don't, but that's not actually observable in any way.
              – Gravity
              Jul 31 '11 at 4:50






            • 5




              primitives are immutable? is that new in Java 7?
              – Carlos Heuberger
              Aug 22 '11 at 11:26






            • 2




              @CarlosHeuberger, "primitives are immutable?". The point is that you can pretend that 'primitives' are actually (mutable) references to immutable objects.
              – Aaron McDaid
              Jul 30 '15 at 16:29






            • 4




              Pointers are immutable, primitives in general are mutable. String is also not a primitive, it is an object. Moreover, the underlying structure of the String is a mutable array. The only immutable thing about it is the length, that being the inherent nature of arrays.
              – kingfrito_5005
              Aug 12 '15 at 18:44













            up vote
            582
            down vote










            up vote
            582
            down vote









            Java is always pass by value, with no exceptions, ever.



            So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java never provides direct access to the values of objects themselves, in any circumstances. The only access to objects is through a reference to that object. Because Java objects are always accessed through a reference, rather than directly, it is common to talk about fields and variables and method arguments as being objects, when pedantically they are only references to objects. The confusion stems from this (strictly speaking, incorrect) change in nomenclature.



            So, when calling a method




            • For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive (for example, 3).

            • For objects, the pass by value is the value of the reference to the object.


            So if you have doSomething(foo) and public void doSomething(Foo foo) { .. } the two Foos have copied references that point to the same objects.



            Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.





            share














            Java is always pass by value, with no exceptions, ever.



            So how is it that anyone can be at all confused by this, and believe that Java is pass by reference, or think they have an example of Java acting as pass by reference? The key point is that Java never provides direct access to the values of objects themselves, in any circumstances. The only access to objects is through a reference to that object. Because Java objects are always accessed through a reference, rather than directly, it is common to talk about fields and variables and method arguments as being objects, when pedantically they are only references to objects. The confusion stems from this (strictly speaking, incorrect) change in nomenclature.



            So, when calling a method




            • For primitive arguments (int, long, etc.), the pass by value is the actual value of the primitive (for example, 3).

            • For objects, the pass by value is the value of the reference to the object.


            So if you have doSomething(foo) and public void doSomething(Foo foo) { .. } the two Foos have copied references that point to the same objects.



            Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.






            share













            share


            share








            edited Jan 22 '16 at 3:37


























            community wiki





            4 revs, 4 users 40%
            SCdF









            • 7




              Since the values of the primitives are immutable (like String), the difference between the two cases is not really relevant.
              – Paŭlo Ebermann
              Feb 3 '11 at 1:23






            • 4




              Exactly. For all you can tell via observable JVM behavior, primitives could be being passed by reference and could live on the heap. They don't, but that's not actually observable in any way.
              – Gravity
              Jul 31 '11 at 4:50






            • 5




              primitives are immutable? is that new in Java 7?
              – Carlos Heuberger
              Aug 22 '11 at 11:26






            • 2




              @CarlosHeuberger, "primitives are immutable?". The point is that you can pretend that 'primitives' are actually (mutable) references to immutable objects.
              – Aaron McDaid
              Jul 30 '15 at 16:29






            • 4




              Pointers are immutable, primitives in general are mutable. String is also not a primitive, it is an object. Moreover, the underlying structure of the String is a mutable array. The only immutable thing about it is the length, that being the inherent nature of arrays.
              – kingfrito_5005
              Aug 12 '15 at 18:44














            • 7




              Since the values of the primitives are immutable (like String), the difference between the two cases is not really relevant.
              – Paŭlo Ebermann
              Feb 3 '11 at 1:23






            • 4




              Exactly. For all you can tell via observable JVM behavior, primitives could be being passed by reference and could live on the heap. They don't, but that's not actually observable in any way.
              – Gravity
              Jul 31 '11 at 4:50






            • 5




              primitives are immutable? is that new in Java 7?
              – Carlos Heuberger
              Aug 22 '11 at 11:26






            • 2




              @CarlosHeuberger, "primitives are immutable?". The point is that you can pretend that 'primitives' are actually (mutable) references to immutable objects.
              – Aaron McDaid
              Jul 30 '15 at 16:29






            • 4




              Pointers are immutable, primitives in general are mutable. String is also not a primitive, it is an object. Moreover, the underlying structure of the String is a mutable array. The only immutable thing about it is the length, that being the inherent nature of arrays.
              – kingfrito_5005
              Aug 12 '15 at 18:44








            7




            7




            Since the values of the primitives are immutable (like String), the difference between the two cases is not really relevant.
            – Paŭlo Ebermann
            Feb 3 '11 at 1:23




            Since the values of the primitives are immutable (like String), the difference between the two cases is not really relevant.
            – Paŭlo Ebermann
            Feb 3 '11 at 1:23




            4




            4




            Exactly. For all you can tell via observable JVM behavior, primitives could be being passed by reference and could live on the heap. They don't, but that's not actually observable in any way.
            – Gravity
            Jul 31 '11 at 4:50




            Exactly. For all you can tell via observable JVM behavior, primitives could be being passed by reference and could live on the heap. They don't, but that's not actually observable in any way.
            – Gravity
            Jul 31 '11 at 4:50




            5




            5




            primitives are immutable? is that new in Java 7?
            – Carlos Heuberger
            Aug 22 '11 at 11:26




            primitives are immutable? is that new in Java 7?
            – Carlos Heuberger
            Aug 22 '11 at 11:26




            2




            2




            @CarlosHeuberger, "primitives are immutable?". The point is that you can pretend that 'primitives' are actually (mutable) references to immutable objects.
            – Aaron McDaid
            Jul 30 '15 at 16:29




            @CarlosHeuberger, "primitives are immutable?". The point is that you can pretend that 'primitives' are actually (mutable) references to immutable objects.
            – Aaron McDaid
            Jul 30 '15 at 16:29




            4




            4




            Pointers are immutable, primitives in general are mutable. String is also not a primitive, it is an object. Moreover, the underlying structure of the String is a mutable array. The only immutable thing about it is the length, that being the inherent nature of arrays.
            – kingfrito_5005
            Aug 12 '15 at 18:44




            Pointers are immutable, primitives in general are mutable. String is also not a primitive, it is an object. Moreover, the underlying structure of the String is a mutable array. The only immutable thing about it is the length, that being the inherent nature of arrays.
            – kingfrito_5005
            Aug 12 '15 at 18:44










            up vote
            285
            down vote













            Java passes references by value.



            So you can't change the reference that gets passed in.





            share



















            • 25




              But the thing that keeps getting repeated "you can't change the value of objects passed in arguments" is clearly false. You may not be able to make them refer to a different object, but you can change their contents by calling their methods. IMO this means you lose all the benefits of references, and gain no additional guarantees.
              – Timmmm
              Jul 24 '11 at 19:13






            • 31




              I never said "you can't change the value of objects passed in arguments". I will say "You can't change the value of the object reference passed in as a method argument", which is a true statement about the Java language. Obviously you can change the state of the object (as long as it's not immutable).
              – ScArcher2
              Aug 1 '11 at 14:19








            • 16




              Keep in mind that you cannot actually pass objects in java; the objects stay on the heap. Pointers to the objects can be passed (which get copied onto the stack frame for the called method). So you never change the passed-in value (the pointer), but you're free to follow it and change the thing on the heap to which it points. That's pass-by-value.
              – Scott Stanchfield
              Jan 26 '12 at 22:17






            • 5




              Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
              – John Strickler
              Mar 12 '14 at 17:38






            • 2




              Java does not pass an object, it passes the value of the pointer to the object. This creates a new pointer to that memory location of the original object in a new variable. If you change the value (the memory address it points to) of this pointer variable in a method, then the original pointer used in the method caller remains unmodified. If you are calling the parameter a reference then the fact that it is a copy of the original reference, not the original reference itself such that there are now two references to the object means that it is pass-by-value
              – theferrit32
              Nov 19 '14 at 16:38

















            up vote
            285
            down vote













            Java passes references by value.



            So you can't change the reference that gets passed in.





            share



















            • 25




              But the thing that keeps getting repeated "you can't change the value of objects passed in arguments" is clearly false. You may not be able to make them refer to a different object, but you can change their contents by calling their methods. IMO this means you lose all the benefits of references, and gain no additional guarantees.
              – Timmmm
              Jul 24 '11 at 19:13






            • 31




              I never said "you can't change the value of objects passed in arguments". I will say "You can't change the value of the object reference passed in as a method argument", which is a true statement about the Java language. Obviously you can change the state of the object (as long as it's not immutable).
              – ScArcher2
              Aug 1 '11 at 14:19








            • 16




              Keep in mind that you cannot actually pass objects in java; the objects stay on the heap. Pointers to the objects can be passed (which get copied onto the stack frame for the called method). So you never change the passed-in value (the pointer), but you're free to follow it and change the thing on the heap to which it points. That's pass-by-value.
              – Scott Stanchfield
              Jan 26 '12 at 22:17






            • 5




              Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
              – John Strickler
              Mar 12 '14 at 17:38






            • 2




              Java does not pass an object, it passes the value of the pointer to the object. This creates a new pointer to that memory location of the original object in a new variable. If you change the value (the memory address it points to) of this pointer variable in a method, then the original pointer used in the method caller remains unmodified. If you are calling the parameter a reference then the fact that it is a copy of the original reference, not the original reference itself such that there are now two references to the object means that it is pass-by-value
              – theferrit32
              Nov 19 '14 at 16:38















            up vote
            285
            down vote










            up vote
            285
            down vote









            Java passes references by value.



            So you can't change the reference that gets passed in.





            share














            Java passes references by value.



            So you can't change the reference that gets passed in.






            share













            share


            share








            answered Sep 2 '08 at 20:20


























            community wiki





            ScArcher2









            • 25




              But the thing that keeps getting repeated "you can't change the value of objects passed in arguments" is clearly false. You may not be able to make them refer to a different object, but you can change their contents by calling their methods. IMO this means you lose all the benefits of references, and gain no additional guarantees.
              – Timmmm
              Jul 24 '11 at 19:13






            • 31




              I never said "you can't change the value of objects passed in arguments". I will say "You can't change the value of the object reference passed in as a method argument", which is a true statement about the Java language. Obviously you can change the state of the object (as long as it's not immutable).
              – ScArcher2
              Aug 1 '11 at 14:19








            • 16




              Keep in mind that you cannot actually pass objects in java; the objects stay on the heap. Pointers to the objects can be passed (which get copied onto the stack frame for the called method). So you never change the passed-in value (the pointer), but you're free to follow it and change the thing on the heap to which it points. That's pass-by-value.
              – Scott Stanchfield
              Jan 26 '12 at 22:17






            • 5




              Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
              – John Strickler
              Mar 12 '14 at 17:38






            • 2




              Java does not pass an object, it passes the value of the pointer to the object. This creates a new pointer to that memory location of the original object in a new variable. If you change the value (the memory address it points to) of this pointer variable in a method, then the original pointer used in the method caller remains unmodified. If you are calling the parameter a reference then the fact that it is a copy of the original reference, not the original reference itself such that there are now two references to the object means that it is pass-by-value
              – theferrit32
              Nov 19 '14 at 16:38
















            • 25




              But the thing that keeps getting repeated "you can't change the value of objects passed in arguments" is clearly false. You may not be able to make them refer to a different object, but you can change their contents by calling their methods. IMO this means you lose all the benefits of references, and gain no additional guarantees.
              – Timmmm
              Jul 24 '11 at 19:13






            • 31




              I never said "you can't change the value of objects passed in arguments". I will say "You can't change the value of the object reference passed in as a method argument", which is a true statement about the Java language. Obviously you can change the state of the object (as long as it's not immutable).
              – ScArcher2
              Aug 1 '11 at 14:19








            • 16




              Keep in mind that you cannot actually pass objects in java; the objects stay on the heap. Pointers to the objects can be passed (which get copied onto the stack frame for the called method). So you never change the passed-in value (the pointer), but you're free to follow it and change the thing on the heap to which it points. That's pass-by-value.
              – Scott Stanchfield
              Jan 26 '12 at 22:17






            • 5




              Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
              – John Strickler
              Mar 12 '14 at 17:38






            • 2




              Java does not pass an object, it passes the value of the pointer to the object. This creates a new pointer to that memory location of the original object in a new variable. If you change the value (the memory address it points to) of this pointer variable in a method, then the original pointer used in the method caller remains unmodified. If you are calling the parameter a reference then the fact that it is a copy of the original reference, not the original reference itself such that there are now two references to the object means that it is pass-by-value
              – theferrit32
              Nov 19 '14 at 16:38










            25




            25




            But the thing that keeps getting repeated "you can't change the value of objects passed in arguments" is clearly false. You may not be able to make them refer to a different object, but you can change their contents by calling their methods. IMO this means you lose all the benefits of references, and gain no additional guarantees.
            – Timmmm
            Jul 24 '11 at 19:13




            But the thing that keeps getting repeated "you can't change the value of objects passed in arguments" is clearly false. You may not be able to make them refer to a different object, but you can change their contents by calling their methods. IMO this means you lose all the benefits of references, and gain no additional guarantees.
            – Timmmm
            Jul 24 '11 at 19:13




            31




            31




            I never said "you can't change the value of objects passed in arguments". I will say "You can't change the value of the object reference passed in as a method argument", which is a true statement about the Java language. Obviously you can change the state of the object (as long as it's not immutable).
            – ScArcher2
            Aug 1 '11 at 14:19






            I never said "you can't change the value of objects passed in arguments". I will say "You can't change the value of the object reference passed in as a method argument", which is a true statement about the Java language. Obviously you can change the state of the object (as long as it's not immutable).
            – ScArcher2
            Aug 1 '11 at 14:19






            16




            16




            Keep in mind that you cannot actually pass objects in java; the objects stay on the heap. Pointers to the objects can be passed (which get copied onto the stack frame for the called method). So you never change the passed-in value (the pointer), but you're free to follow it and change the thing on the heap to which it points. That's pass-by-value.
            – Scott Stanchfield
            Jan 26 '12 at 22:17




            Keep in mind that you cannot actually pass objects in java; the objects stay on the heap. Pointers to the objects can be passed (which get copied onto the stack frame for the called method). So you never change the passed-in value (the pointer), but you're free to follow it and change the thing on the heap to which it points. That's pass-by-value.
            – Scott Stanchfield
            Jan 26 '12 at 22:17




            5




            5




            Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
            – John Strickler
            Mar 12 '14 at 17:38




            Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument...
            – John Strickler
            Mar 12 '14 at 17:38




            2




            2




            Java does not pass an object, it passes the value of the pointer to the object. This creates a new pointer to that memory location of the original object in a new variable. If you change the value (the memory address it points to) of this pointer variable in a method, then the original pointer used in the method caller remains unmodified. If you are calling the parameter a reference then the fact that it is a copy of the original reference, not the original reference itself such that there are now two references to the object means that it is pass-by-value
            – theferrit32
            Nov 19 '14 at 16:38






            Java does not pass an object, it passes the value of the pointer to the object. This creates a new pointer to that memory location of the original object in a new variable. If you change the value (the memory address it points to) of this pointer variable in a method, then the original pointer used in the method caller remains unmodified. If you are calling the parameter a reference then the fact that it is a copy of the original reference, not the original reference itself such that there are now two references to the object means that it is pass-by-value
            – theferrit32
            Nov 19 '14 at 16:38












            up vote
            205
            down vote













            I feel like arguing about "pass-by-reference vs pass-by-value" is not super-helpful.



            If you say, "Java is pass-by-whatever (reference/value)", in either case, you're not provide a complete answer. Here's some additional information that will hopefully aid in understanding what's happening in memory.



            Crash course on stack/heap before we get to the Java implementation:
            Values go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria.
            Memory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.



            Okay. First off, local primitives go on the stack. So this code:



            int x = 3;
            float y = 101.1f;
            boolean amIAwesome = true;


            results in this:



            primitives on the stack



            When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word "pointer". Whatever. Just know that the address of the object goes on the stack.



            Like so:



            int problems = 99;
            String name = "Jay-Z";


            a b*7ch aint one!



            An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.



            JButton marxBros = new JButton[3];
            marxBros[0] = new JButton("Groucho");
            marxBros[1] = new JButton("Zeppo");
            marxBros[2] = new JButton("Harpo");


            marx brothers



            So, what gets passed in when you call a method? If you pass in an object, what you're actually passing in is the address of the object. Some might say the "value" of the address, and some say it's just a reference to the object. This is the genesis of the holy war between "reference" and "value" proponents. What you call it isn't as important as that you understand that what's getting passed in is the address to the object.



            private static void shout(String name){
            System.out.println("There goes " + name + "!");
            }

            public static void main(String args){
            String hisName = "John J. Jingleheimerschmitz";
            String myName = hisName;
            shout(myName);
            }


            One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier hisName, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call shout(): a new stack frame is created and a new identifier, name is created and assigned the address of the already-existing String.



            la da di da da da da



            So, value, reference? You say "potato".





            share



















            • 6




              However, you should have followed up with a more complex example where a function appears to alter a variable to whose address it has a reference.
              – Brian Peterson
              Nov 1 '13 at 6:53






            • 28




              People are not "dancing around the real issue" of stack vs heap, because that's not the real issue. It's an implementation detail at best, and downright wrong at worst. (It's quite possible for objects to live on the stack; google "escape analysis". And a huge number of objects contain primitives that probably don't live on the stack.) The real issue is exactly the difference between reference types and value types -- in particular, that the value of a reference-type variable is a reference, not the object it refers to.
              – cHao
              Dec 18 '13 at 4:48








            • 8




              It's an "implementation detail" in that Java is never required to actually show you where an object lives in memory, and in fact seems determined to avoid leaking that info. It could put the object on the stack, and you'd never know. If you care, you're focusing on the wrong thing -- and in this case, that means ignoring the real issue.
              – cHao
              Dec 18 '13 at 14:38








            • 9




              And either way, "primitives go on the stack" is incorrect. Primitive local variables go on the stack. (If they haven't been optimized away, of course.) But then, so do local reference variables. And primitive members defined within an object live wherever the object lives.
              – cHao
              Dec 18 '13 at 14:55








            • 9




              Agree with the comments here. Stack/heap is a side issue, and not relevant. Some variables may be on the stack, some are in static memory (static variables), and plenty live on the heap (all object member variables). NONE of these variables can be passed by reference: from a called method it is NEVER possible to change the value of a variable that is passed as an argument. Therefore, there is no pass-by-reference in Java.
              – fishinear
              Mar 2 '14 at 15:37















            up vote
            205
            down vote













            I feel like arguing about "pass-by-reference vs pass-by-value" is not super-helpful.



            If you say, "Java is pass-by-whatever (reference/value)", in either case, you're not provide a complete answer. Here's some additional information that will hopefully aid in understanding what's happening in memory.



            Crash course on stack/heap before we get to the Java implementation:
            Values go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria.
            Memory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.



            Okay. First off, local primitives go on the stack. So this code:



            int x = 3;
            float y = 101.1f;
            boolean amIAwesome = true;


            results in this:



            primitives on the stack



            When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word "pointer". Whatever. Just know that the address of the object goes on the stack.



            Like so:



            int problems = 99;
            String name = "Jay-Z";


            a b*7ch aint one!



            An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.



            JButton marxBros = new JButton[3];
            marxBros[0] = new JButton("Groucho");
            marxBros[1] = new JButton("Zeppo");
            marxBros[2] = new JButton("Harpo");


            marx brothers



            So, what gets passed in when you call a method? If you pass in an object, what you're actually passing in is the address of the object. Some might say the "value" of the address, and some say it's just a reference to the object. This is the genesis of the holy war between "reference" and "value" proponents. What you call it isn't as important as that you understand that what's getting passed in is the address to the object.



            private static void shout(String name){
            System.out.println("There goes " + name + "!");
            }

            public static void main(String args){
            String hisName = "John J. Jingleheimerschmitz";
            String myName = hisName;
            shout(myName);
            }


            One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier hisName, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call shout(): a new stack frame is created and a new identifier, name is created and assigned the address of the already-existing String.



            la da di da da da da



            So, value, reference? You say "potato".





            share



















            • 6




              However, you should have followed up with a more complex example where a function appears to alter a variable to whose address it has a reference.
              – Brian Peterson
              Nov 1 '13 at 6:53






            • 28




              People are not "dancing around the real issue" of stack vs heap, because that's not the real issue. It's an implementation detail at best, and downright wrong at worst. (It's quite possible for objects to live on the stack; google "escape analysis". And a huge number of objects contain primitives that probably don't live on the stack.) The real issue is exactly the difference between reference types and value types -- in particular, that the value of a reference-type variable is a reference, not the object it refers to.
              – cHao
              Dec 18 '13 at 4:48








            • 8




              It's an "implementation detail" in that Java is never required to actually show you where an object lives in memory, and in fact seems determined to avoid leaking that info. It could put the object on the stack, and you'd never know. If you care, you're focusing on the wrong thing -- and in this case, that means ignoring the real issue.
              – cHao
              Dec 18 '13 at 14:38








            • 9




              And either way, "primitives go on the stack" is incorrect. Primitive local variables go on the stack. (If they haven't been optimized away, of course.) But then, so do local reference variables. And primitive members defined within an object live wherever the object lives.
              – cHao
              Dec 18 '13 at 14:55








            • 9




              Agree with the comments here. Stack/heap is a side issue, and not relevant. Some variables may be on the stack, some are in static memory (static variables), and plenty live on the heap (all object member variables). NONE of these variables can be passed by reference: from a called method it is NEVER possible to change the value of a variable that is passed as an argument. Therefore, there is no pass-by-reference in Java.
              – fishinear
              Mar 2 '14 at 15:37













            up vote
            205
            down vote










            up vote
            205
            down vote









            I feel like arguing about "pass-by-reference vs pass-by-value" is not super-helpful.



            If you say, "Java is pass-by-whatever (reference/value)", in either case, you're not provide a complete answer. Here's some additional information that will hopefully aid in understanding what's happening in memory.



            Crash course on stack/heap before we get to the Java implementation:
            Values go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria.
            Memory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.



            Okay. First off, local primitives go on the stack. So this code:



            int x = 3;
            float y = 101.1f;
            boolean amIAwesome = true;


            results in this:



            primitives on the stack



            When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word "pointer". Whatever. Just know that the address of the object goes on the stack.



            Like so:



            int problems = 99;
            String name = "Jay-Z";


            a b*7ch aint one!



            An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.



            JButton marxBros = new JButton[3];
            marxBros[0] = new JButton("Groucho");
            marxBros[1] = new JButton("Zeppo");
            marxBros[2] = new JButton("Harpo");


            marx brothers



            So, what gets passed in when you call a method? If you pass in an object, what you're actually passing in is the address of the object. Some might say the "value" of the address, and some say it's just a reference to the object. This is the genesis of the holy war between "reference" and "value" proponents. What you call it isn't as important as that you understand that what's getting passed in is the address to the object.



            private static void shout(String name){
            System.out.println("There goes " + name + "!");
            }

            public static void main(String args){
            String hisName = "John J. Jingleheimerschmitz";
            String myName = hisName;
            shout(myName);
            }


            One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier hisName, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call shout(): a new stack frame is created and a new identifier, name is created and assigned the address of the already-existing String.



            la da di da da da da



            So, value, reference? You say "potato".





            share














            I feel like arguing about "pass-by-reference vs pass-by-value" is not super-helpful.



            If you say, "Java is pass-by-whatever (reference/value)", in either case, you're not provide a complete answer. Here's some additional information that will hopefully aid in understanding what's happening in memory.



            Crash course on stack/heap before we get to the Java implementation:
            Values go on and off the stack in a nice orderly fashion, like a stack of plates at a cafeteria.
            Memory in the heap (also known as dynamic memory) is haphazard and disorganized. The JVM just finds space wherever it can, and frees it up as the variables that use it are no longer needed.



            Okay. First off, local primitives go on the stack. So this code:



            int x = 3;
            float y = 101.1f;
            boolean amIAwesome = true;


            results in this:



            primitives on the stack



            When you declare and instantiate an object. The actual object goes on the heap. What goes on the stack? The address of the object on the heap. C++ programmers would call this a pointer, but some Java developers are against the word "pointer". Whatever. Just know that the address of the object goes on the stack.



            Like so:



            int problems = 99;
            String name = "Jay-Z";


            a b*7ch aint one!



            An array is an object, so it goes on the heap as well. And what about the objects in the array? They get their own heap space, and the address of each object goes inside the array.



            JButton marxBros = new JButton[3];
            marxBros[0] = new JButton("Groucho");
            marxBros[1] = new JButton("Zeppo");
            marxBros[2] = new JButton("Harpo");


            marx brothers



            So, what gets passed in when you call a method? If you pass in an object, what you're actually passing in is the address of the object. Some might say the "value" of the address, and some say it's just a reference to the object. This is the genesis of the holy war between "reference" and "value" proponents. What you call it isn't as important as that you understand that what's getting passed in is the address to the object.



            private static void shout(String name){
            System.out.println("There goes " + name + "!");
            }

            public static void main(String args){
            String hisName = "John J. Jingleheimerschmitz";
            String myName = hisName;
            shout(myName);
            }


            One String gets created and space for it is allocated in the heap, and the address to the string is stored on the stack and given the identifier hisName, since the address of the second String is the same as the first, no new String is created and no new heap space is allocated, but a new identifier is created on the stack. Then we call shout(): a new stack frame is created and a new identifier, name is created and assigned the address of the already-existing String.



            la da di da da da da



            So, value, reference? You say "potato".






            share













            share


            share








            edited Jan 4 at 16:18


























            community wiki





            6 revs, 4 users 97%
            cutmancometh









            • 6




              However, you should have followed up with a more complex example where a function appears to alter a variable to whose address it has a reference.
              – Brian Peterson
              Nov 1 '13 at 6:53






            • 28




              People are not "dancing around the real issue" of stack vs heap, because that's not the real issue. It's an implementation detail at best, and downright wrong at worst. (It's quite possible for objects to live on the stack; google "escape analysis". And a huge number of objects contain primitives that probably don't live on the stack.) The real issue is exactly the difference between reference types and value types -- in particular, that the value of a reference-type variable is a reference, not the object it refers to.
              – cHao
              Dec 18 '13 at 4:48








            • 8




              It's an "implementation detail" in that Java is never required to actually show you where an object lives in memory, and in fact seems determined to avoid leaking that info. It could put the object on the stack, and you'd never know. If you care, you're focusing on the wrong thing -- and in this case, that means ignoring the real issue.
              – cHao
              Dec 18 '13 at 14:38








            • 9




              And either way, "primitives go on the stack" is incorrect. Primitive local variables go on the stack. (If they haven't been optimized away, of course.) But then, so do local reference variables. And primitive members defined within an object live wherever the object lives.
              – cHao
              Dec 18 '13 at 14:55








            • 9




              Agree with the comments here. Stack/heap is a side issue, and not relevant. Some variables may be on the stack, some are in static memory (static variables), and plenty live on the heap (all object member variables). NONE of these variables can be passed by reference: from a called method it is NEVER possible to change the value of a variable that is passed as an argument. Therefore, there is no pass-by-reference in Java.
              – fishinear
              Mar 2 '14 at 15:37














            • 6




              However, you should have followed up with a more complex example where a function appears to alter a variable to whose address it has a reference.
              – Brian Peterson
              Nov 1 '13 at 6:53






            • 28




              People are not "dancing around the real issue" of stack vs heap, because that's not the real issue. It's an implementation detail at best, and downright wrong at worst. (It's quite possible for objects to live on the stack; google "escape analysis". And a huge number of objects contain primitives that probably don't live on the stack.) The real issue is exactly the difference between reference types and value types -- in particular, that the value of a reference-type variable is a reference, not the object it refers to.
              – cHao
              Dec 18 '13 at 4:48








            • 8




              It's an "implementation detail" in that Java is never required to actually show you where an object lives in memory, and in fact seems determined to avoid leaking that info. It could put the object on the stack, and you'd never know. If you care, you're focusing on the wrong thing -- and in this case, that means ignoring the real issue.
              – cHao
              Dec 18 '13 at 14:38








            • 9




              And either way, "primitives go on the stack" is incorrect. Primitive local variables go on the stack. (If they haven't been optimized away, of course.) But then, so do local reference variables. And primitive members defined within an object live wherever the object lives.
              – cHao
              Dec 18 '13 at 14:55








            • 9




              Agree with the comments here. Stack/heap is a side issue, and not relevant. Some variables may be on the stack, some are in static memory (static variables), and plenty live on the heap (all object member variables). NONE of these variables can be passed by reference: from a called method it is NEVER possible to change the value of a variable that is passed as an argument. Therefore, there is no pass-by-reference in Java.
              – fishinear
              Mar 2 '14 at 15:37








            6




            6




            However, you should have followed up with a more complex example where a function appears to alter a variable to whose address it has a reference.
            – Brian Peterson
            Nov 1 '13 at 6:53




            However, you should have followed up with a more complex example where a function appears to alter a variable to whose address it has a reference.
            – Brian Peterson
            Nov 1 '13 at 6:53




            28




            28




            People are not "dancing around the real issue" of stack vs heap, because that's not the real issue. It's an implementation detail at best, and downright wrong at worst. (It's quite possible for objects to live on the stack; google "escape analysis". And a huge number of objects contain primitives that probably don't live on the stack.) The real issue is exactly the difference between reference types and value types -- in particular, that the value of a reference-type variable is a reference, not the object it refers to.
            – cHao
            Dec 18 '13 at 4:48






            People are not "dancing around the real issue" of stack vs heap, because that's not the real issue. It's an implementation detail at best, and downright wrong at worst. (It's quite possible for objects to live on the stack; google "escape analysis". And a huge number of objects contain primitives that probably don't live on the stack.) The real issue is exactly the difference between reference types and value types -- in particular, that the value of a reference-type variable is a reference, not the object it refers to.
            – cHao
            Dec 18 '13 at 4:48






            8




            8




            It's an "implementation detail" in that Java is never required to actually show you where an object lives in memory, and in fact seems determined to avoid leaking that info. It could put the object on the stack, and you'd never know. If you care, you're focusing on the wrong thing -- and in this case, that means ignoring the real issue.
            – cHao
            Dec 18 '13 at 14:38






            It's an "implementation detail" in that Java is never required to actually show you where an object lives in memory, and in fact seems determined to avoid leaking that info. It could put the object on the stack, and you'd never know. If you care, you're focusing on the wrong thing -- and in this case, that means ignoring the real issue.
            – cHao
            Dec 18 '13 at 14:38






            9




            9




            And either way, "primitives go on the stack" is incorrect. Primitive local variables go on the stack. (If they haven't been optimized away, of course.) But then, so do local reference variables. And primitive members defined within an object live wherever the object lives.
            – cHao
            Dec 18 '13 at 14:55






            And either way, "primitives go on the stack" is incorrect. Primitive local variables go on the stack. (If they haven't been optimized away, of course.) But then, so do local reference variables. And primitive members defined within an object live wherever the object lives.
            – cHao
            Dec 18 '13 at 14:55






            9




            9




            Agree with the comments here. Stack/heap is a side issue, and not relevant. Some variables may be on the stack, some are in static memory (static variables), and plenty live on the heap (all object member variables). NONE of these variables can be passed by reference: from a called method it is NEVER possible to change the value of a variable that is passed as an argument. Therefore, there is no pass-by-reference in Java.
            – fishinear
            Mar 2 '14 at 15:37




            Agree with the comments here. Stack/heap is a side issue, and not relevant. Some variables may be on the stack, some are in static memory (static variables), and plenty live on the heap (all object member variables). NONE of these variables can be passed by reference: from a called method it is NEVER possible to change the value of a variable that is passed as an argument. Therefore, there is no pass-by-reference in Java.
            – fishinear
            Mar 2 '14 at 15:37










            up vote
            168
            down vote













            Just to show the contrast, compare the following C++ and Java snippets:



            In C++: Note: Bad code - memory leaks! But it demonstrates the point.



            void cppMethod(int val, int &ref, Dog obj, Dog &objRef, Dog *objPtr, Dog *&objPtrRef)
            {
            val = 7; // Modifies the copy
            ref = 7; // Modifies the original variable
            obj.SetName("obj"); // Modifies the copy of Dog passed
            objRef.SetName("objRef"); // Modifies the original Dog passed
            objPtr->SetName("objPtr"); // Modifies the original Dog pointed to
            // by the copy of the pointer passed.
            objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
            // leaving the original object alone.
            objPtrRef->SetName("objRefPtr"); // Modifies the original Dog pointed to
            // by the original pointer passed.
            objPtrRef = new Dog("newObjPtrRef"); // Modifies the original pointer passed
            }

            int main()
            {
            int a = 0;
            int b = 0;
            Dog d0 = Dog("d0");
            Dog d1 = Dog("d1");
            Dog *d2 = new Dog("d2");
            Dog *d3 = new Dog("d3");
            cppMethod(a, b, d0, d1, d2, d3);
            // a is still set to 0
            // b is now set to 7
            // d0 still have name "d0"
            // d1 now has name "objRef"
            // d2 now has name "objPtr"
            // d3 now has name "newObjPtrRef"
            }


            In Java,



            public static void javaMethod(int val, Dog objPtr)
            {
            val = 7; // Modifies the copy
            objPtr.SetName("objPtr") // Modifies the original Dog pointed to
            // by the copy of the pointer passed.
            objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
            // leaving the original object alone.
            }

            public static void main()
            {
            int a = 0;
            Dog d0 = new Dog("d0");
            javaMethod(a, d0);
            // a is still set to 0
            // d0 now has name "objPtr"
            }


            Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.





            share



















            • 7




              +1 I would also add Dog **objPtrPtr to the C++ example, that way we can modify what the pointer "points to".
              – Amro
              Jul 2 '14 at 3:59










            • This is one of the best answers I have seen so far. It mostly avoids the irrelevant semantics argument of "reference vs value of the reference" present elsewhere and instead discusses the mechanics of what actually happens. I had to give most other "pass-by-value" answers -1 because of their self-contradictory or factually false content, but this one gets +1 instead.
              – Aaron
              Aug 2 '17 at 15:32










            • But this doesn't answer for the given question in Java. As the matter of fact, everything in Java's method is Pass By Value, nothing more.
              – tauitdnmd
              Nov 6 at 9:11















            up vote
            168
            down vote













            Just to show the contrast, compare the following C++ and Java snippets:



            In C++: Note: Bad code - memory leaks! But it demonstrates the point.



            void cppMethod(int val, int &ref, Dog obj, Dog &objRef, Dog *objPtr, Dog *&objPtrRef)
            {
            val = 7; // Modifies the copy
            ref = 7; // Modifies the original variable
            obj.SetName("obj"); // Modifies the copy of Dog passed
            objRef.SetName("objRef"); // Modifies the original Dog passed
            objPtr->SetName("objPtr"); // Modifies the original Dog pointed to
            // by the copy of the pointer passed.
            objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
            // leaving the original object alone.
            objPtrRef->SetName("objRefPtr"); // Modifies the original Dog pointed to
            // by the original pointer passed.
            objPtrRef = new Dog("newObjPtrRef"); // Modifies the original pointer passed
            }

            int main()
            {
            int a = 0;
            int b = 0;
            Dog d0 = Dog("d0");
            Dog d1 = Dog("d1");
            Dog *d2 = new Dog("d2");
            Dog *d3 = new Dog("d3");
            cppMethod(a, b, d0, d1, d2, d3);
            // a is still set to 0
            // b is now set to 7
            // d0 still have name "d0"
            // d1 now has name "objRef"
            // d2 now has name "objPtr"
            // d3 now has name "newObjPtrRef"
            }


            In Java,



            public static void javaMethod(int val, Dog objPtr)
            {
            val = 7; // Modifies the copy
            objPtr.SetName("objPtr") // Modifies the original Dog pointed to
            // by the copy of the pointer passed.
            objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
            // leaving the original object alone.
            }

            public static void main()
            {
            int a = 0;
            Dog d0 = new Dog("d0");
            javaMethod(a, d0);
            // a is still set to 0
            // d0 now has name "objPtr"
            }


            Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.





            share



















            • 7




              +1 I would also add Dog **objPtrPtr to the C++ example, that way we can modify what the pointer "points to".
              – Amro
              Jul 2 '14 at 3:59










            • This is one of the best answers I have seen so far. It mostly avoids the irrelevant semantics argument of "reference vs value of the reference" present elsewhere and instead discusses the mechanics of what actually happens. I had to give most other "pass-by-value" answers -1 because of their self-contradictory or factually false content, but this one gets +1 instead.
              – Aaron
              Aug 2 '17 at 15:32










            • But this doesn't answer for the given question in Java. As the matter of fact, everything in Java's method is Pass By Value, nothing more.
              – tauitdnmd
              Nov 6 at 9:11













            up vote
            168
            down vote










            up vote
            168
            down vote









            Just to show the contrast, compare the following C++ and Java snippets:



            In C++: Note: Bad code - memory leaks! But it demonstrates the point.



            void cppMethod(int val, int &ref, Dog obj, Dog &objRef, Dog *objPtr, Dog *&objPtrRef)
            {
            val = 7; // Modifies the copy
            ref = 7; // Modifies the original variable
            obj.SetName("obj"); // Modifies the copy of Dog passed
            objRef.SetName("objRef"); // Modifies the original Dog passed
            objPtr->SetName("objPtr"); // Modifies the original Dog pointed to
            // by the copy of the pointer passed.
            objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
            // leaving the original object alone.
            objPtrRef->SetName("objRefPtr"); // Modifies the original Dog pointed to
            // by the original pointer passed.
            objPtrRef = new Dog("newObjPtrRef"); // Modifies the original pointer passed
            }

            int main()
            {
            int a = 0;
            int b = 0;
            Dog d0 = Dog("d0");
            Dog d1 = Dog("d1");
            Dog *d2 = new Dog("d2");
            Dog *d3 = new Dog("d3");
            cppMethod(a, b, d0, d1, d2, d3);
            // a is still set to 0
            // b is now set to 7
            // d0 still have name "d0"
            // d1 now has name "objRef"
            // d2 now has name "objPtr"
            // d3 now has name "newObjPtrRef"
            }


            In Java,



            public static void javaMethod(int val, Dog objPtr)
            {
            val = 7; // Modifies the copy
            objPtr.SetName("objPtr") // Modifies the original Dog pointed to
            // by the copy of the pointer passed.
            objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
            // leaving the original object alone.
            }

            public static void main()
            {
            int a = 0;
            Dog d0 = new Dog("d0");
            javaMethod(a, d0);
            // a is still set to 0
            // d0 now has name "objPtr"
            }


            Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.





            share














            Just to show the contrast, compare the following C++ and Java snippets:



            In C++: Note: Bad code - memory leaks! But it demonstrates the point.



            void cppMethod(int val, int &ref, Dog obj, Dog &objRef, Dog *objPtr, Dog *&objPtrRef)
            {
            val = 7; // Modifies the copy
            ref = 7; // Modifies the original variable
            obj.SetName("obj"); // Modifies the copy of Dog passed
            objRef.SetName("objRef"); // Modifies the original Dog passed
            objPtr->SetName("objPtr"); // Modifies the original Dog pointed to
            // by the copy of the pointer passed.
            objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
            // leaving the original object alone.
            objPtrRef->SetName("objRefPtr"); // Modifies the original Dog pointed to
            // by the original pointer passed.
            objPtrRef = new Dog("newObjPtrRef"); // Modifies the original pointer passed
            }

            int main()
            {
            int a = 0;
            int b = 0;
            Dog d0 = Dog("d0");
            Dog d1 = Dog("d1");
            Dog *d2 = new Dog("d2");
            Dog *d3 = new Dog("d3");
            cppMethod(a, b, d0, d1, d2, d3);
            // a is still set to 0
            // b is now set to 7
            // d0 still have name "d0"
            // d1 now has name "objRef"
            // d2 now has name "objPtr"
            // d3 now has name "newObjPtrRef"
            }


            In Java,



            public static void javaMethod(int val, Dog objPtr)
            {
            val = 7; // Modifies the copy
            objPtr.SetName("objPtr") // Modifies the original Dog pointed to
            // by the copy of the pointer passed.
            objPtr = new Dog("newObjPtr"); // Modifies the copy of the pointer,
            // leaving the original object alone.
            }

            public static void main()
            {
            int a = 0;
            Dog d0 = new Dog("d0");
            javaMethod(a, d0);
            // a is still set to 0
            // d0 now has name "objPtr"
            }


            Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.






            share













            share


            share








            edited Sep 27 '16 at 14:42


























            community wiki





            4 revs, 4 users 94%
            Eclipse









            • 7




              +1 I would also add Dog **objPtrPtr to the C++ example, that way we can modify what the pointer "points to".
              – Amro
              Jul 2 '14 at 3:59










            • This is one of the best answers I have seen so far. It mostly avoids the irrelevant semantics argument of "reference vs value of the reference" present elsewhere and instead discusses the mechanics of what actually happens. I had to give most other "pass-by-value" answers -1 because of their self-contradictory or factually false content, but this one gets +1 instead.
              – Aaron
              Aug 2 '17 at 15:32










            • But this doesn't answer for the given question in Java. As the matter of fact, everything in Java's method is Pass By Value, nothing more.
              – tauitdnmd
              Nov 6 at 9:11














            • 7




              +1 I would also add Dog **objPtrPtr to the C++ example, that way we can modify what the pointer "points to".
              – Amro
              Jul 2 '14 at 3:59










            • This is one of the best answers I have seen so far. It mostly avoids the irrelevant semantics argument of "reference vs value of the reference" present elsewhere and instead discusses the mechanics of what actually happens. I had to give most other "pass-by-value" answers -1 because of their self-contradictory or factually false content, but this one gets +1 instead.
              – Aaron
              Aug 2 '17 at 15:32










            • But this doesn't answer for the given question in Java. As the matter of fact, everything in Java's method is Pass By Value, nothing more.
              – tauitdnmd
              Nov 6 at 9:11








            7




            7




            +1 I would also add Dog **objPtrPtr to the C++ example, that way we can modify what the pointer "points to".
            – Amro
            Jul 2 '14 at 3:59




            +1 I would also add Dog **objPtrPtr to the C++ example, that way we can modify what the pointer "points to".
            – Amro
            Jul 2 '14 at 3:59












            This is one of the best answers I have seen so far. It mostly avoids the irrelevant semantics argument of "reference vs value of the reference" present elsewhere and instead discusses the mechanics of what actually happens. I had to give most other "pass-by-value" answers -1 because of their self-contradictory or factually false content, but this one gets +1 instead.
            – Aaron
            Aug 2 '17 at 15:32




            This is one of the best answers I have seen so far. It mostly avoids the irrelevant semantics argument of "reference vs value of the reference" present elsewhere and instead discusses the mechanics of what actually happens. I had to give most other "pass-by-value" answers -1 because of their self-contradictory or factually false content, but this one gets +1 instead.
            – Aaron
            Aug 2 '17 at 15:32












            But this doesn't answer for the given question in Java. As the matter of fact, everything in Java's method is Pass By Value, nothing more.
            – tauitdnmd
            Nov 6 at 9:11




            But this doesn't answer for the given question in Java. As the matter of fact, everything in Java's method is Pass By Value, nothing more.
            – tauitdnmd
            Nov 6 at 9:11










            up vote
            147
            down vote













            Java passes references to objects by value.





            share























            • As simple as that !
              – Ivan Kaloyanov
              May 30 at 10:39















            up vote
            147
            down vote













            Java passes references to objects by value.





            share























            • As simple as that !
              – Ivan Kaloyanov
              May 30 at 10:39













            up vote
            147
            down vote










            up vote
            147
            down vote









            Java passes references to objects by value.





            share














            Java passes references to objects by value.






            share













            share


            share








            answered Sep 2 '08 at 20:23


























            community wiki





            John Channing













            • As simple as that !
              – Ivan Kaloyanov
              May 30 at 10:39


















            • As simple as that !
              – Ivan Kaloyanov
              May 30 at 10:39
















            As simple as that !
            – Ivan Kaloyanov
            May 30 at 10:39




            As simple as that !
            – Ivan Kaloyanov
            May 30 at 10:39










            up vote
            140
            down vote













            Basically, reassigning Object parameters doesn't affect the argument, e.g.,



            private void foo(Object bar) {
            bar = null;
            }

            public static void main(String args) {
            String baz = "Hah!";
            foo(baz);
            System.out.println(baz);
            }


            will print out "Hah!" instead of null. The reason this works is because bar is a copy of the value of baz, which is just a reference to "Hah!". If it were the actual reference itself, then foo would have redefined baz to null.





            share



















            • 7




              I would rather say that bar is a copy of the reference baz (or baz alias), that points initially to the same object.
              – MaxZoom
              Feb 11 '15 at 5:36















            up vote
            140
            down vote













            Basically, reassigning Object parameters doesn't affect the argument, e.g.,



            private void foo(Object bar) {
            bar = null;
            }

            public static void main(String args) {
            String baz = "Hah!";
            foo(baz);
            System.out.println(baz);
            }


            will print out "Hah!" instead of null. The reason this works is because bar is a copy of the value of baz, which is just a reference to "Hah!". If it were the actual reference itself, then foo would have redefined baz to null.





            share



















            • 7




              I would rather say that bar is a copy of the reference baz (or baz alias), that points initially to the same object.
              – MaxZoom
              Feb 11 '15 at 5:36













            up vote
            140
            down vote










            up vote
            140
            down vote









            Basically, reassigning Object parameters doesn't affect the argument, e.g.,



            private void foo(Object bar) {
            bar = null;
            }

            public static void main(String args) {
            String baz = "Hah!";
            foo(baz);
            System.out.println(baz);
            }


            will print out "Hah!" instead of null. The reason this works is because bar is a copy of the value of baz, which is just a reference to "Hah!". If it were the actual reference itself, then foo would have redefined baz to null.





            share














            Basically, reassigning Object parameters doesn't affect the argument, e.g.,



            private void foo(Object bar) {
            bar = null;
            }

            public static void main(String args) {
            String baz = "Hah!";
            foo(baz);
            System.out.println(baz);
            }


            will print out "Hah!" instead of null. The reason this works is because bar is a copy of the value of baz, which is just a reference to "Hah!". If it were the actual reference itself, then foo would have redefined baz to null.






            share













            share


            share








            edited Jul 10 at 9:57


























            community wiki





            2 revs, 2 users 97%
            Hank Gay









            • 7




              I would rather say that bar is a copy of the reference baz (or baz alias), that points initially to the same object.
              – MaxZoom
              Feb 11 '15 at 5:36














            • 7




              I would rather say that bar is a copy of the reference baz (or baz alias), that points initially to the same object.
              – MaxZoom
              Feb 11 '15 at 5:36








            7




            7




            I would rather say that bar is a copy of the reference baz (or baz alias), that points initially to the same object.
            – MaxZoom
            Feb 11 '15 at 5:36




            I would rather say that bar is a copy of the reference baz (or baz alias), that points initially to the same object.
            – MaxZoom
            Feb 11 '15 at 5:36










            up vote
            139
            down vote













            I can't believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term call by sharing (also known as call by object-sharing and call by object) for this specific case of "call by value where the value is a reference".





            share



















            • 2




              I like this distinction in nomenclature. It's unfortunate that Java supports call by sharing for objects, but not call by value (as does C++). Java supports call by value only for primitive data types and not composite data types.
              – Derek Mahar
              Sep 8 '10 at 14:16






            • 2




              I really don't think we needed an extra term - it's simply pass-by-value for a specific type of value. Would adding "call by primitive" add any clarification?
              – Scott Stanchfield
              Oct 25 '10 at 20:03






            • 7




              Call by Sharing
              – wulfgarpro
              Sep 16 '11 at 0:29












            • So I can pass-by-reference by sharing some global context object, or even passing a context object that contains other references? I still pass-by-value, but at least I have access to references I can modify and make them point to something else.
              – YoYo
              Jan 8 '16 at 0:14















            up vote
            139
            down vote













            I can't believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term call by sharing (also known as call by object-sharing and call by object) for this specific case of "call by value where the value is a reference".





            share



















            • 2




              I like this distinction in nomenclature. It's unfortunate that Java supports call by sharing for objects, but not call by value (as does C++). Java supports call by value only for primitive data types and not composite data types.
              – Derek Mahar
              Sep 8 '10 at 14:16






            • 2




              I really don't think we needed an extra term - it's simply pass-by-value for a specific type of value. Would adding "call by primitive" add any clarification?
              – Scott Stanchfield
              Oct 25 '10 at 20:03






            • 7




              Call by Sharing
              – wulfgarpro
              Sep 16 '11 at 0:29












            • So I can pass-by-reference by sharing some global context object, or even passing a context object that contains other references? I still pass-by-value, but at least I have access to references I can modify and make them point to something else.
              – YoYo
              Jan 8 '16 at 0:14













            up vote
            139
            down vote










            up vote
            139
            down vote









            I can't believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term call by sharing (also known as call by object-sharing and call by object) for this specific case of "call by value where the value is a reference".





            share














            I can't believe that nobody mentioned Barbara Liskov yet. When she designed CLU in 1974, she ran into this same terminology problem, and she invented the term call by sharing (also known as call by object-sharing and call by object) for this specific case of "call by value where the value is a reference".






            share













            share


            share








            answered Sep 7 '10 at 22:07


























            community wiki





            Jörg W Mittag









            • 2




              I like this distinction in nomenclature. It's unfortunate that Java supports call by sharing for objects, but not call by value (as does C++). Java supports call by value only for primitive data types and not composite data types.
              – Derek Mahar
              Sep 8 '10 at 14:16






            • 2




              I really don't think we needed an extra term - it's simply pass-by-value for a specific type of value. Would adding "call by primitive" add any clarification?
              – Scott Stanchfield
              Oct 25 '10 at 20:03






            • 7




              Call by Sharing
              – wulfgarpro
              Sep 16 '11 at 0:29












            • So I can pass-by-reference by sharing some global context object, or even passing a context object that contains other references? I still pass-by-value, but at least I have access to references I can modify and make them point to something else.
              – YoYo
              Jan 8 '16 at 0:14














            • 2




              I like this distinction in nomenclature. It's unfortunate that Java supports call by sharing for objects, but not call by value (as does C++). Java supports call by value only for primitive data types and not composite data types.
              – Derek Mahar
              Sep 8 '10 at 14:16






            • 2




              I really don't think we needed an extra term - it's simply pass-by-value for a specific type of value. Would adding "call by primitive" add any clarification?
              – Scott Stanchfield
              Oct 25 '10 at 20:03






            • 7




              Call by Sharing
              – wulfgarpro
              Sep 16 '11 at 0:29












            • So I can pass-by-reference by sharing some global context object, or even passing a context object that contains other references? I still pass-by-value, but at least I have access to references I can modify and make them point to something else.
              – YoYo
              Jan 8 '16 at 0:14








            2




            2




            I like this distinction in nomenclature. It's unfortunate that Java supports call by sharing for objects, but not call by value (as does C++). Java supports call by value only for primitive data types and not composite data types.
            – Derek Mahar
            Sep 8 '10 at 14:16




            I like this distinction in nomenclature. It's unfortunate that Java supports call by sharing for objects, but not call by value (as does C++). Java supports call by value only for primitive data types and not composite data types.
            – Derek Mahar
            Sep 8 '10 at 14:16




            2




            2




            I really don't think we needed an extra term - it's simply pass-by-value for a specific type of value. Would adding "call by primitive" add any clarification?
            – Scott Stanchfield
            Oct 25 '10 at 20:03




            I really don't think we needed an extra term - it's simply pass-by-value for a specific type of value. Would adding "call by primitive" add any clarification?
            – Scott Stanchfield
            Oct 25 '10 at 20:03




            7




            7




            Call by Sharing
            – wulfgarpro
            Sep 16 '11 at 0:29






            Call by Sharing
            – wulfgarpro
            Sep 16 '11 at 0:29














            So I can pass-by-reference by sharing some global context object, or even passing a context object that contains other references? I still pass-by-value, but at least I have access to references I can modify and make them point to something else.
            – YoYo
            Jan 8 '16 at 0:14




            So I can pass-by-reference by sharing some global context object, or even passing a context object that contains other references? I still pass-by-value, but at least I have access to references I can modify and make them point to something else.
            – YoYo
            Jan 8 '16 at 0:14










            up vote
            99
            down vote













            The crux of the matter is that the word reference in the expression "pass by reference" means something completely different from the usual meaning of the word reference in Java.



            Usually in Java reference means a a reference to an object. But the technical terms pass by reference/value from programming language theory is talking about a reference to the memory cell holding the variable, which is something completely different.





            share



















            • 10




              Colloquially called a pointer.
              – Prof. Falken
              Feb 9 '11 at 9:50






            • 7




              @Gevorg - Then what is a "NullPointerException"?
              – Hot Licks
              Sep 22 '13 at 14:09






            • 4




              @Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException.
              – JacquesB
              Sep 23 '13 at 14:08






            • 4




              It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding.
              – Hot Licks
              Sep 23 '13 at 15:46










            • I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity.
              – moronkreacionz
              Dec 29 '15 at 21:36















            up vote
            99
            down vote













            The crux of the matter is that the word reference in the expression "pass by reference" means something completely different from the usual meaning of the word reference in Java.



            Usually in Java reference means a a reference to an object. But the technical terms pass by reference/value from programming language theory is talking about a reference to the memory cell holding the variable, which is something completely different.





            share



















            • 10




              Colloquially called a pointer.
              – Prof. Falken
              Feb 9 '11 at 9:50






            • 7




              @Gevorg - Then what is a "NullPointerException"?
              – Hot Licks
              Sep 22 '13 at 14:09






            • 4




              @Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException.
              – JacquesB
              Sep 23 '13 at 14:08






            • 4




              It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding.
              – Hot Licks
              Sep 23 '13 at 15:46










            • I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity.
              – moronkreacionz
              Dec 29 '15 at 21:36













            up vote
            99
            down vote










            up vote
            99
            down vote









            The crux of the matter is that the word reference in the expression "pass by reference" means something completely different from the usual meaning of the word reference in Java.



            Usually in Java reference means a a reference to an object. But the technical terms pass by reference/value from programming language theory is talking about a reference to the memory cell holding the variable, which is something completely different.





            share














            The crux of the matter is that the word reference in the expression "pass by reference" means something completely different from the usual meaning of the word reference in Java.



            Usually in Java reference means a a reference to an object. But the technical terms pass by reference/value from programming language theory is talking about a reference to the memory cell holding the variable, which is something completely different.






            share













            share


            share








            edited Feb 6 at 10:18


























            community wiki





            4 revs, 2 users 89%
            JacquesB









            • 10




              Colloquially called a pointer.
              – Prof. Falken
              Feb 9 '11 at 9:50






            • 7




              @Gevorg - Then what is a "NullPointerException"?
              – Hot Licks
              Sep 22 '13 at 14:09






            • 4




              @Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException.
              – JacquesB
              Sep 23 '13 at 14:08






            • 4




              It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding.
              – Hot Licks
              Sep 23 '13 at 15:46










            • I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity.
              – moronkreacionz
              Dec 29 '15 at 21:36














            • 10




              Colloquially called a pointer.
              – Prof. Falken
              Feb 9 '11 at 9:50






            • 7




              @Gevorg - Then what is a "NullPointerException"?
              – Hot Licks
              Sep 22 '13 at 14:09






            • 4




              @Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException.
              – JacquesB
              Sep 23 '13 at 14:08






            • 4




              It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding.
              – Hot Licks
              Sep 23 '13 at 15:46










            • I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity.
              – moronkreacionz
              Dec 29 '15 at 21:36








            10




            10




            Colloquially called a pointer.
            – Prof. Falken
            Feb 9 '11 at 9:50




            Colloquially called a pointer.
            – Prof. Falken
            Feb 9 '11 at 9:50




            7




            7




            @Gevorg - Then what is a "NullPointerException"?
            – Hot Licks
            Sep 22 '13 at 14:09




            @Gevorg - Then what is a "NullPointerException"?
            – Hot Licks
            Sep 22 '13 at 14:09




            4




            4




            @Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException.
            – JacquesB
            Sep 23 '13 at 14:08




            @Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException.
            – JacquesB
            Sep 23 '13 at 14:08




            4




            4




            It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding.
            – Hot Licks
            Sep 23 '13 at 15:46




            It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding.
            – Hot Licks
            Sep 23 '13 at 15:46












            I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity.
            – moronkreacionz
            Dec 29 '15 at 21:36




            I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity.
            – moronkreacionz
            Dec 29 '15 at 21:36










            up vote
            75
            down vote













            In java everything is reference, so when you have something like:
            Point pnt1 = new Point(0,0); Java does following:




            1. Creates new Point object

            2. Creates new Point reference and initialize that reference to point (refer to) on previously created Point object.

            3. From here, through Point object life, you will access to that object through pnt1
              reference. So we can say that in Java you manipulate object through its reference.



            enter image description here



            Java doesn't pass method arguments by reference; it passes them by value. I will use example from this site:



            public static void tricky(Point arg1, Point arg2) {
            arg1.x = 100;
            arg1.y = 100;
            Point temp = arg1;
            arg1 = arg2;
            arg2 = temp;
            }
            public static void main(String args) {
            Point pnt1 = new Point(0,0);
            Point pnt2 = new Point(0,0);
            System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            System.out.println(" ");
            tricky(pnt1,pnt2);
            System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y);
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            }


            Flow of the program:



            Point pnt1 = new Point(0,0);
            Point pnt2 = new Point(0,0);


            Creating two different Point object with two different reference associated.
            enter image description here



            System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y); 
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            System.out.println(" ");


            As expected output will be:



            X1: 0     Y1: 0
            X2: 0 Y2: 0


            On this line 'pass-by-value' goes into the play...



            tricky(pnt1,pnt2);           public void tricky(Point arg1, Point arg2);


            References pnt1 and pnt2 are passed by value to the tricky method, which means that now yours references pnt1 and pnt2 have their copies named arg1 and arg2.So pnt1 and arg1 points to the same object. (Same for the pnt2 and arg2)
            enter image description here



            In the tricky method:



             arg1.x = 100;
            arg1.y = 100;


            enter image description here



            Next in the tricky method



            Point temp = arg1;
            arg1 = arg2;
            arg2 = temp;


            Here, you first create new temp Point reference which will point on same place like arg1 reference. Then you move reference arg1 to point to the same place like arg2 reference.
            Finally arg2 will point to the same place like temp.



            enter image description here



            From here scope of tricky method is gone and you don't have access any more to the references: arg1, arg2, temp. But important note is that everything you do with these references when they are 'in life' will permanently affect object on which they are point to.



            So after executing method tricky, when you return to main, you have this situation:
            enter image description here



            So now, completely execution of program will be:



            X1: 0         Y1: 0
            X2: 0 Y2: 0
            X1: 100 Y1: 100
            X2: 0 Y2: 0




            share



















            • 7




              In java when you say "In java everything is reference" you mean all objects are passed by reference. Primitive data types are not passed by reference.
              – Eric
              Oct 22 '15 at 6:42










            • I am able to print swapped value in main method. in trickey method , add the following statement arg1.x = 1; arg1.y = 1; arg2.x = 2; arg2.y = 2; so, as arg1 now holding of pnt2 refrence and arg2 holding now pnt1 reference, so, its printing X1: 2 Y1: 2 X2: 1 Y2: 1
              – Shahid Ghafoor
              Dec 20 '16 at 1:29

















            up vote
            75
            down vote













            In java everything is reference, so when you have something like:
            Point pnt1 = new Point(0,0); Java does following:




            1. Creates new Point object

            2. Creates new Point reference and initialize that reference to point (refer to) on previously created Point object.

            3. From here, through Point object life, you will access to that object through pnt1
              reference. So we can say that in Java you manipulate object through its reference.



            enter image description here



            Java doesn't pass method arguments by reference; it passes them by value. I will use example from this site:



            public static void tricky(Point arg1, Point arg2) {
            arg1.x = 100;
            arg1.y = 100;
            Point temp = arg1;
            arg1 = arg2;
            arg2 = temp;
            }
            public static void main(String args) {
            Point pnt1 = new Point(0,0);
            Point pnt2 = new Point(0,0);
            System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            System.out.println(" ");
            tricky(pnt1,pnt2);
            System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y);
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            }


            Flow of the program:



            Point pnt1 = new Point(0,0);
            Point pnt2 = new Point(0,0);


            Creating two different Point object with two different reference associated.
            enter image description here



            System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y); 
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            System.out.println(" ");


            As expected output will be:



            X1: 0     Y1: 0
            X2: 0 Y2: 0


            On this line 'pass-by-value' goes into the play...



            tricky(pnt1,pnt2);           public void tricky(Point arg1, Point arg2);


            References pnt1 and pnt2 are passed by value to the tricky method, which means that now yours references pnt1 and pnt2 have their copies named arg1 and arg2.So pnt1 and arg1 points to the same object. (Same for the pnt2 and arg2)
            enter image description here



            In the tricky method:



             arg1.x = 100;
            arg1.y = 100;


            enter image description here



            Next in the tricky method



            Point temp = arg1;
            arg1 = arg2;
            arg2 = temp;


            Here, you first create new temp Point reference which will point on same place like arg1 reference. Then you move reference arg1 to point to the same place like arg2 reference.
            Finally arg2 will point to the same place like temp.



            enter image description here



            From here scope of tricky method is gone and you don't have access any more to the references: arg1, arg2, temp. But important note is that everything you do with these references when they are 'in life' will permanently affect object on which they are point to.



            So after executing method tricky, when you return to main, you have this situation:
            enter image description here



            So now, completely execution of program will be:



            X1: 0         Y1: 0
            X2: 0 Y2: 0
            X1: 100 Y1: 100
            X2: 0 Y2: 0




            share



















            • 7




              In java when you say "In java everything is reference" you mean all objects are passed by reference. Primitive data types are not passed by reference.
              – Eric
              Oct 22 '15 at 6:42










            • I am able to print swapped value in main method. in trickey method , add the following statement arg1.x = 1; arg1.y = 1; arg2.x = 2; arg2.y = 2; so, as arg1 now holding of pnt2 refrence and arg2 holding now pnt1 reference, so, its printing X1: 2 Y1: 2 X2: 1 Y2: 1
              – Shahid Ghafoor
              Dec 20 '16 at 1:29















            up vote
            75
            down vote










            up vote
            75
            down vote









            In java everything is reference, so when you have something like:
            Point pnt1 = new Point(0,0); Java does following:




            1. Creates new Point object

            2. Creates new Point reference and initialize that reference to point (refer to) on previously created Point object.

            3. From here, through Point object life, you will access to that object through pnt1
              reference. So we can say that in Java you manipulate object through its reference.



            enter image description here



            Java doesn't pass method arguments by reference; it passes them by value. I will use example from this site:



            public static void tricky(Point arg1, Point arg2) {
            arg1.x = 100;
            arg1.y = 100;
            Point temp = arg1;
            arg1 = arg2;
            arg2 = temp;
            }
            public static void main(String args) {
            Point pnt1 = new Point(0,0);
            Point pnt2 = new Point(0,0);
            System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            System.out.println(" ");
            tricky(pnt1,pnt2);
            System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y);
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            }


            Flow of the program:



            Point pnt1 = new Point(0,0);
            Point pnt2 = new Point(0,0);


            Creating two different Point object with two different reference associated.
            enter image description here



            System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y); 
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            System.out.println(" ");


            As expected output will be:



            X1: 0     Y1: 0
            X2: 0 Y2: 0


            On this line 'pass-by-value' goes into the play...



            tricky(pnt1,pnt2);           public void tricky(Point arg1, Point arg2);


            References pnt1 and pnt2 are passed by value to the tricky method, which means that now yours references pnt1 and pnt2 have their copies named arg1 and arg2.So pnt1 and arg1 points to the same object. (Same for the pnt2 and arg2)
            enter image description here



            In the tricky method:



             arg1.x = 100;
            arg1.y = 100;


            enter image description here



            Next in the tricky method



            Point temp = arg1;
            arg1 = arg2;
            arg2 = temp;


            Here, you first create new temp Point reference which will point on same place like arg1 reference. Then you move reference arg1 to point to the same place like arg2 reference.
            Finally arg2 will point to the same place like temp.



            enter image description here



            From here scope of tricky method is gone and you don't have access any more to the references: arg1, arg2, temp. But important note is that everything you do with these references when they are 'in life' will permanently affect object on which they are point to.



            So after executing method tricky, when you return to main, you have this situation:
            enter image description here



            So now, completely execution of program will be:



            X1: 0         Y1: 0
            X2: 0 Y2: 0
            X1: 100 Y1: 100
            X2: 0 Y2: 0




            share














            In java everything is reference, so when you have something like:
            Point pnt1 = new Point(0,0); Java does following:




            1. Creates new Point object

            2. Creates new Point reference and initialize that reference to point (refer to) on previously created Point object.

            3. From here, through Point object life, you will access to that object through pnt1
              reference. So we can say that in Java you manipulate object through its reference.



            enter image description here



            Java doesn't pass method arguments by reference; it passes them by value. I will use example from this site:



            public static void tricky(Point arg1, Point arg2) {
            arg1.x = 100;
            arg1.y = 100;
            Point temp = arg1;
            arg1 = arg2;
            arg2 = temp;
            }
            public static void main(String args) {
            Point pnt1 = new Point(0,0);
            Point pnt2 = new Point(0,0);
            System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y);
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            System.out.println(" ");
            tricky(pnt1,pnt2);
            System.out.println("X1: " + pnt1.x + " Y1:" + pnt1.y);
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            }


            Flow of the program:



            Point pnt1 = new Point(0,0);
            Point pnt2 = new Point(0,0);


            Creating two different Point object with two different reference associated.
            enter image description here



            System.out.println("X1: " + pnt1.x + " Y1: " +pnt1.y); 
            System.out.println("X2: " + pnt2.x + " Y2: " +pnt2.y);
            System.out.println(" ");


            As expected output will be:



            X1: 0     Y1: 0
            X2: 0 Y2: 0


            On this line 'pass-by-value' goes into the play...



            tricky(pnt1,pnt2);           public void tricky(Point arg1, Point arg2);


            References pnt1 and pnt2 are passed by value to the tricky method, which means that now yours references pnt1 and pnt2 have their copies named arg1 and arg2.So pnt1 and arg1 points to the same object. (Same for the pnt2 and arg2)
            enter image description here



            In the tricky method:



             arg1.x = 100;
            arg1.y = 100;


            enter image description here



            Next in the tricky method



            Point temp = arg1;
            arg1 = arg2;
            arg2 = temp;


            Here, you first create new temp Point reference which will point on same place like arg1 reference. Then you move reference arg1 to point to the same place like arg2 reference.
            Finally arg2 will point to the same place like temp.



            enter image description here



            From here scope of tricky method is gone and you don't have access any more to the references: arg1, arg2, temp. But important note is that everything you do with these references when they are 'in life' will permanently affect object on which they are point to.



            So after executing method tricky, when you return to main, you have this situation:
            enter image description here



            So now, completely execution of program will be:



            X1: 0         Y1: 0
            X2: 0 Y2: 0
            X1: 100 Y1: 100
            X2: 0 Y2: 0





            share













            share


            share








            edited Sep 16 '15 at 15:18


























            community wiki





            3 revs, 3 users 91%
            Srle









            • 7




              In java when you say "In java everything is reference" you mean all objects are passed by reference. Primitive data types are not passed by reference.
              – Eric
              Oct 22 '15 at 6:42










            • I am able to print swapped value in main method. in trickey method , add the following statement arg1.x = 1; arg1.y = 1; arg2.x = 2; arg2.y = 2; so, as arg1 now holding of pnt2 refrence and arg2 holding now pnt1 reference, so, its printing X1: 2 Y1: 2 X2: 1 Y2: 1
              – Shahid Ghafoor
              Dec 20 '16 at 1:29
















            • 7




              In java when you say "In java everything is reference" you mean all objects are passed by reference. Primitive data types are not passed by reference.
              – Eric
              Oct 22 '15 at 6:42










            • I am able to print swapped value in main method. in trickey method , add the following statement arg1.x = 1; arg1.y = 1; arg2.x = 2; arg2.y = 2; so, as arg1 now holding of pnt2 refrence and arg2 holding now pnt1 reference, so, its printing X1: 2 Y1: 2 X2: 1 Y2: 1
              – Shahid Ghafoor
              Dec 20 '16 at 1:29










            7




            7




            In java when you say "In java everything is reference" you mean all objects are passed by reference. Primitive data types are not passed by reference.
            – Eric
            Oct 22 '15 at 6:42




            In java when you say "In java everything is reference" you mean all objects are passed by reference. Primitive data types are not passed by reference.
            – Eric
            Oct 22 '15 at 6:42












            I am able to print swapped value in main method. in trickey method , add the following statement arg1.x = 1; arg1.y = 1; arg2.x = 2; arg2.y = 2; so, as arg1 now holding of pnt2 refrence and arg2 holding now pnt1 reference, so, its printing X1: 2 Y1: 2 X2: 1 Y2: 1
            – Shahid Ghafoor
            Dec 20 '16 at 1:29






            I am able to print swapped value in main method. in trickey method , add the following statement arg1.x = 1; arg1.y = 1; arg2.x = 2; arg2.y = 2; so, as arg1 now holding of pnt2 refrence and arg2 holding now pnt1 reference, so, its printing X1: 2 Y1: 2 X2: 1 Y2: 1
            – Shahid Ghafoor
            Dec 20 '16 at 1:29












            up vote
            64
            down vote













            A reference is always a value when represented, no matter what language you use.



            Getting an outside of the box view, let's look at Assembly or some low level memory management. At the CPU level a reference to anything immediately becomes a value if it gets written to memory or to one of the CPU registers. (That is why pointer is a good definition. It is a value, which has a purpose at the same time).



            Data in memory has a Location and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a Name to certain Location (aka variable), but when compiling the code, the assembler simply replaces Name with the designated location just like your browser replaces domain names with IP addresses.



            Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).



            Lets say we have a variable Foo, its Location is at the 47th byte in memory and its Value is 5. We have another variable Ref2Foo which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two Values.
            If you use them as references then to reach to 5 we have to travel:



            (Name)[Location] -> [Value at the Location]
            ---------------------
            (Ref2Foo)[223] -> 47
            (Foo)[47] -> 5


            This is how jump-tables work.



            If we want to call a method/function/procedure with Foo's value, there are a few possible way to pass the variable to the method, depending on the language and its several method invocation modes:




            1. 5 gets copied to one of the CPU registers (ie. EAX).

            2. 5 gets PUSHd to the stack.

            3. 47 gets copied to one of the CPU registers

            4. 47 PUSHd to the stack.

            5. 223 gets copied to one of the CPU registers.

            6. 223 gets PUSHd to the stack.


            In every cases above a value - a copy of an existing value - has been created, it is now upto the receiving method to handle it. When you write "Foo" inside the method, it is either read out from EAX, or automatically dereferenced, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a reference is a value when represented, because a reference is a value that has to be processed (at language level).



            Now we have passed Foo to the method:




            • in case 1. and 2. if you change Foo (Foo = 9) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.

            • in case 3. and 4. if you use default language constructs and change Foo (Foo = 11), it could change Foo globally (depends on the language, ie. Java or like Pascal's procedure findMin(x, y, z: integer;var m: integer);). However if the language allows you to circumvent the dereference process, you can change 47, say to 49. At that point Foo seems to have been changed if you read it, because you have changed the local pointer to it. And if you were to modify this Foo inside the method (Foo = 12) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at 47). BUT Foo's value of 47 did not change globally, only the one inside the method, because 47 was also a copy to the method.

            • in case 5. and 6. if you modify 223 inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was copied. However if you are able to dereference Ref2Foo (that is 223), reach to and modify the pointed value 47, say, to 49, it will affect Foo globally, because in this case the methods got a copy of 223 but the referenced 47 exists only once, and changing that to 49 will lead every Ref2Foo double-dereferencing to a wrong value.


            Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only pass-by-reference.



            Strict pass-by-value is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller's view) and a few languages allows to modify the Value of the reference itself.



            So in short and in Java's own terminology, Java is pass-by-value where value can be: either a real value or a value that is a representation of a reference.





            share























            • In a language with pass-by-reference, the thing which is passed (the reference) is ephemeral; the recipient is not "supposed" to copy it. In Java, passing an array is passed is an "object identifier"--equivalent to a slip of paper which says "Object #24601", when the 24601st object constructed was an array. The recipient can copy "Object #24601" anywhere it wants, and anyone with a slip of paper saying "Object #24601" can do anything it wants with any of the array elements. The pattern of bits that is passed wouldn't actually say "Object #24601", of course, but...
              – supercat
              Jan 10 '14 at 17:02










            • ...the key point is that the recipient of the object-id that identifies the array can store that object-id wherever it wants and give it to whomever it wants, and any recipient would be able to access or modify the array whenever it wants. By contrast, if an array were passed by reference in a language like Pascal which supports such things, the called method could do whatever it wanted with the array, but could not store the reference in such a way as to allow code to modify the array after it returned.
              – supercat
              Jan 10 '14 at 17:04










            • Indeed, in Pascal you can get the address of every variable, be it passed-by-reference or locally copied, addr does it untyped,@ does it with type, and you can modify the referenced variable later (except locally copied ones). But I don't see the point why you would do that. That slip of paper in your example (Object #24601) is a reference,its purpose is to help find the array in memory, it does not contain any array data in itself. If you restart your program, the same array might get a different object-id even if its content will be the same as it has been in the previous run.
              – karatedog
              Jan 10 '14 at 22:48










            • I'd thought the "@" operator was not part of standard Pascal, but was implemented as a common extension. Is it part of the standard? My point was that in a language with true pass-by-ref, and no ability to construct a non-ephemeral pointer to an ephemeral object, code which holds the only reference to an array, anywhere in the universe, before passing the array by reference can know that unless the recipient "cheats" it will still hold the only reference afterward. The only safe way to accomplish that in Java would be to construct a temporary object...
              – supercat
              Jan 10 '14 at 22:52










            • ...which encapsulates an AtomicReference and neither exposes the reference nor its target, but instead includes methods to do things to the target; once the code to which the object was passed returns, the AtomicReference [to which its creator kept a direct reference] should be invalidated and abandoned. That would provide the proper semantics, but it would be slow and icky.
              – supercat
              Jan 10 '14 at 22:54















            up vote
            64
            down vote













            A reference is always a value when represented, no matter what language you use.



            Getting an outside of the box view, let's look at Assembly or some low level memory management. At the CPU level a reference to anything immediately becomes a value if it gets written to memory or to one of the CPU registers. (That is why pointer is a good definition. It is a value, which has a purpose at the same time).



            Data in memory has a Location and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a Name to certain Location (aka variable), but when compiling the code, the assembler simply replaces Name with the designated location just like your browser replaces domain names with IP addresses.



            Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).



            Lets say we have a variable Foo, its Location is at the 47th byte in memory and its Value is 5. We have another variable Ref2Foo which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two Values.
            If you use them as references then to reach to 5 we have to travel:



            (Name)[Location] -> [Value at the Location]
            ---------------------
            (Ref2Foo)[223] -> 47
            (Foo)[47] -> 5


            This is how jump-tables work.



            If we want to call a method/function/procedure with Foo's value, there are a few possible way to pass the variable to the method, depending on the language and its several method invocation modes:




            1. 5 gets copied to one of the CPU registers (ie. EAX).

            2. 5 gets PUSHd to the stack.

            3. 47 gets copied to one of the CPU registers

            4. 47 PUSHd to the stack.

            5. 223 gets copied to one of the CPU registers.

            6. 223 gets PUSHd to the stack.


            In every cases above a value - a copy of an existing value - has been created, it is now upto the receiving method to handle it. When you write "Foo" inside the method, it is either read out from EAX, or automatically dereferenced, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a reference is a value when represented, because a reference is a value that has to be processed (at language level).



            Now we have passed Foo to the method:




            • in case 1. and 2. if you change Foo (Foo = 9) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.

            • in case 3. and 4. if you use default language constructs and change Foo (Foo = 11), it could change Foo globally (depends on the language, ie. Java or like Pascal's procedure findMin(x, y, z: integer;var m: integer);). However if the language allows you to circumvent the dereference process, you can change 47, say to 49. At that point Foo seems to have been changed if you read it, because you have changed the local pointer to it. And if you were to modify this Foo inside the method (Foo = 12) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at 47). BUT Foo's value of 47 did not change globally, only the one inside the method, because 47 was also a copy to the method.

            • in case 5. and 6. if you modify 223 inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was copied. However if you are able to dereference Ref2Foo (that is 223), reach to and modify the pointed value 47, say, to 49, it will affect Foo globally, because in this case the methods got a copy of 223 but the referenced 47 exists only once, and changing that to 49 will lead every Ref2Foo double-dereferencing to a wrong value.


            Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only pass-by-reference.



            Strict pass-by-value is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller's view) and a few languages allows to modify the Value of the reference itself.



            So in short and in Java's own terminology, Java is pass-by-value where value can be: either a real value or a value that is a representation of a reference.





            share























            • In a language with pass-by-reference, the thing which is passed (the reference) is ephemeral; the recipient is not "supposed" to copy it. In Java, passing an array is passed is an "object identifier"--equivalent to a slip of paper which says "Object #24601", when the 24601st object constructed was an array. The recipient can copy "Object #24601" anywhere it wants, and anyone with a slip of paper saying "Object #24601" can do anything it wants with any of the array elements. The pattern of bits that is passed wouldn't actually say "Object #24601", of course, but...
              – supercat
              Jan 10 '14 at 17:02










            • ...the key point is that the recipient of the object-id that identifies the array can store that object-id wherever it wants and give it to whomever it wants, and any recipient would be able to access or modify the array whenever it wants. By contrast, if an array were passed by reference in a language like Pascal which supports such things, the called method could do whatever it wanted with the array, but could not store the reference in such a way as to allow code to modify the array after it returned.
              – supercat
              Jan 10 '14 at 17:04










            • Indeed, in Pascal you can get the address of every variable, be it passed-by-reference or locally copied, addr does it untyped,@ does it with type, and you can modify the referenced variable later (except locally copied ones). But I don't see the point why you would do that. That slip of paper in your example (Object #24601) is a reference,its purpose is to help find the array in memory, it does not contain any array data in itself. If you restart your program, the same array might get a different object-id even if its content will be the same as it has been in the previous run.
              – karatedog
              Jan 10 '14 at 22:48










            • I'd thought the "@" operator was not part of standard Pascal, but was implemented as a common extension. Is it part of the standard? My point was that in a language with true pass-by-ref, and no ability to construct a non-ephemeral pointer to an ephemeral object, code which holds the only reference to an array, anywhere in the universe, before passing the array by reference can know that unless the recipient "cheats" it will still hold the only reference afterward. The only safe way to accomplish that in Java would be to construct a temporary object...
              – supercat
              Jan 10 '14 at 22:52










            • ...which encapsulates an AtomicReference and neither exposes the reference nor its target, but instead includes methods to do things to the target; once the code to which the object was passed returns, the AtomicReference [to which its creator kept a direct reference] should be invalidated and abandoned. That would provide the proper semantics, but it would be slow and icky.
              – supercat
              Jan 10 '14 at 22:54













            up vote
            64
            down vote










            up vote
            64
            down vote









            A reference is always a value when represented, no matter what language you use.



            Getting an outside of the box view, let's look at Assembly or some low level memory management. At the CPU level a reference to anything immediately becomes a value if it gets written to memory or to one of the CPU registers. (That is why pointer is a good definition. It is a value, which has a purpose at the same time).



            Data in memory has a Location and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a Name to certain Location (aka variable), but when compiling the code, the assembler simply replaces Name with the designated location just like your browser replaces domain names with IP addresses.



            Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).



            Lets say we have a variable Foo, its Location is at the 47th byte in memory and its Value is 5. We have another variable Ref2Foo which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two Values.
            If you use them as references then to reach to 5 we have to travel:



            (Name)[Location] -> [Value at the Location]
            ---------------------
            (Ref2Foo)[223] -> 47
            (Foo)[47] -> 5


            This is how jump-tables work.



            If we want to call a method/function/procedure with Foo's value, there are a few possible way to pass the variable to the method, depending on the language and its several method invocation modes:




            1. 5 gets copied to one of the CPU registers (ie. EAX).

            2. 5 gets PUSHd to the stack.

            3. 47 gets copied to one of the CPU registers

            4. 47 PUSHd to the stack.

            5. 223 gets copied to one of the CPU registers.

            6. 223 gets PUSHd to the stack.


            In every cases above a value - a copy of an existing value - has been created, it is now upto the receiving method to handle it. When you write "Foo" inside the method, it is either read out from EAX, or automatically dereferenced, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a reference is a value when represented, because a reference is a value that has to be processed (at language level).



            Now we have passed Foo to the method:




            • in case 1. and 2. if you change Foo (Foo = 9) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.

            • in case 3. and 4. if you use default language constructs and change Foo (Foo = 11), it could change Foo globally (depends on the language, ie. Java or like Pascal's procedure findMin(x, y, z: integer;var m: integer);). However if the language allows you to circumvent the dereference process, you can change 47, say to 49. At that point Foo seems to have been changed if you read it, because you have changed the local pointer to it. And if you were to modify this Foo inside the method (Foo = 12) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at 47). BUT Foo's value of 47 did not change globally, only the one inside the method, because 47 was also a copy to the method.

            • in case 5. and 6. if you modify 223 inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was copied. However if you are able to dereference Ref2Foo (that is 223), reach to and modify the pointed value 47, say, to 49, it will affect Foo globally, because in this case the methods got a copy of 223 but the referenced 47 exists only once, and changing that to 49 will lead every Ref2Foo double-dereferencing to a wrong value.


            Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only pass-by-reference.



            Strict pass-by-value is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller's view) and a few languages allows to modify the Value of the reference itself.



            So in short and in Java's own terminology, Java is pass-by-value where value can be: either a real value or a value that is a representation of a reference.





            share














            A reference is always a value when represented, no matter what language you use.



            Getting an outside of the box view, let's look at Assembly or some low level memory management. At the CPU level a reference to anything immediately becomes a value if it gets written to memory or to one of the CPU registers. (That is why pointer is a good definition. It is a value, which has a purpose at the same time).



            Data in memory has a Location and at that location there is a value (byte,word, whatever). In Assembly we have a convenient solution to give a Name to certain Location (aka variable), but when compiling the code, the assembler simply replaces Name with the designated location just like your browser replaces domain names with IP addresses.



            Down to the core it is technically impossible to pass a reference to anything in any language without representing it (when it immediately becomes a value).



            Lets say we have a variable Foo, its Location is at the 47th byte in memory and its Value is 5. We have another variable Ref2Foo which is at 223rd byte in memory, and its value will be 47. This Ref2Foo might be a technical variable, not explicitly created by the program. If you just look at 5 and 47 without any other information, you will see just two Values.
            If you use them as references then to reach to 5 we have to travel:



            (Name)[Location] -> [Value at the Location]
            ---------------------
            (Ref2Foo)[223] -> 47
            (Foo)[47] -> 5


            This is how jump-tables work.



            If we want to call a method/function/procedure with Foo's value, there are a few possible way to pass the variable to the method, depending on the language and its several method invocation modes:




            1. 5 gets copied to one of the CPU registers (ie. EAX).

            2. 5 gets PUSHd to the stack.

            3. 47 gets copied to one of the CPU registers

            4. 47 PUSHd to the stack.

            5. 223 gets copied to one of the CPU registers.

            6. 223 gets PUSHd to the stack.


            In every cases above a value - a copy of an existing value - has been created, it is now upto the receiving method to handle it. When you write "Foo" inside the method, it is either read out from EAX, or automatically dereferenced, or double dereferenced, the process depends on how the language works and/or what the type of Foo dictates. This is hidden from the developer until she circumvents the dereferencing process. So a reference is a value when represented, because a reference is a value that has to be processed (at language level).



            Now we have passed Foo to the method:




            • in case 1. and 2. if you change Foo (Foo = 9) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.

            • in case 3. and 4. if you use default language constructs and change Foo (Foo = 11), it could change Foo globally (depends on the language, ie. Java or like Pascal's procedure findMin(x, y, z: integer;var m: integer);). However if the language allows you to circumvent the dereference process, you can change 47, say to 49. At that point Foo seems to have been changed if you read it, because you have changed the local pointer to it. And if you were to modify this Foo inside the method (Foo = 12) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at 47). BUT Foo's value of 47 did not change globally, only the one inside the method, because 47 was also a copy to the method.

            • in case 5. and 6. if you modify 223 inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was copied. However if you are able to dereference Ref2Foo (that is 223), reach to and modify the pointed value 47, say, to 49, it will affect Foo globally, because in this case the methods got a copy of 223 but the referenced 47 exists only once, and changing that to 49 will lead every Ref2Foo double-dereferencing to a wrong value.


            Nitpicking on insignificant details, even languages that do pass-by-reference will pass values to functions, but those functions know that they have to use it for dereferencing purposes. This pass-the-reference-as-value is just hidden from the programmer because it is practically useless and the terminology is only pass-by-reference.



            Strict pass-by-value is also useless, it would mean that a 100 Mbyte array should have to be copied every time we call a method with the array as argument, therefore Java cannot be stricly pass-by-value. Every language would pass a reference to this huge array (as a value) and either employs copy-on-write mechanism if that array can be changed locally inside the method or allows the method (as Java does) to modify the array globally (from the caller's view) and a few languages allows to modify the Value of the reference itself.



            So in short and in Java's own terminology, Java is pass-by-value where value can be: either a real value or a value that is a representation of a reference.






            share













            share


            share








            edited Dec 28 '15 at 7:36


























            community wiki





            6 revs
            karatedog













            • In a language with pass-by-reference, the thing which is passed (the reference) is ephemeral; the recipient is not "supposed" to copy it. In Java, passing an array is passed is an "object identifier"--equivalent to a slip of paper which says "Object #24601", when the 24601st object constructed was an array. The recipient can copy "Object #24601" anywhere it wants, and anyone with a slip of paper saying "Object #24601" can do anything it wants with any of the array elements. The pattern of bits that is passed wouldn't actually say "Object #24601", of course, but...
              – supercat
              Jan 10 '14 at 17:02










            • ...the key point is that the recipient of the object-id that identifies the array can store that object-id wherever it wants and give it to whomever it wants, and any recipient would be able to access or modify the array whenever it wants. By contrast, if an array were passed by reference in a language like Pascal which supports such things, the called method could do whatever it wanted with the array, but could not store the reference in such a way as to allow code to modify the array after it returned.
              – supercat
              Jan 10 '14 at 17:04










            • Indeed, in Pascal you can get the address of every variable, be it passed-by-reference or locally copied, addr does it untyped,@ does it with type, and you can modify the referenced variable later (except locally copied ones). But I don't see the point why you would do that. That slip of paper in your example (Object #24601) is a reference,its purpose is to help find the array in memory, it does not contain any array data in itself. If you restart your program, the same array might get a different object-id even if its content will be the same as it has been in the previous run.
              – karatedog
              Jan 10 '14 at 22:48










            • I'd thought the "@" operator was not part of standard Pascal, but was implemented as a common extension. Is it part of the standard? My point was that in a language with true pass-by-ref, and no ability to construct a non-ephemeral pointer to an ephemeral object, code which holds the only reference to an array, anywhere in the universe, before passing the array by reference can know that unless the recipient "cheats" it will still hold the only reference afterward. The only safe way to accomplish that in Java would be to construct a temporary object...
              – supercat
              Jan 10 '14 at 22:52










            • ...which encapsulates an AtomicReference and neither exposes the reference nor its target, but instead includes methods to do things to the target; once the code to which the object was passed returns, the AtomicReference [to which its creator kept a direct reference] should be invalidated and abandoned. That would provide the proper semantics, but it would be slow and icky.
              – supercat
              Jan 10 '14 at 22:54


















            • In a language with pass-by-reference, the thing which is passed (the reference) is ephemeral; the recipient is not "supposed" to copy it. In Java, passing an array is passed is an "object identifier"--equivalent to a slip of paper which says "Object #24601", when the 24601st object constructed was an array. The recipient can copy "Object #24601" anywhere it wants, and anyone with a slip of paper saying "Object #24601" can do anything it wants with any of the array elements. The pattern of bits that is passed wouldn't actually say "Object #24601", of course, but...
              – supercat
              Jan 10 '14 at 17:02










            • ...the key point is that the recipient of the object-id that identifies the array can store that object-id wherever it wants and give it to whomever it wants, and any recipient would be able to access or modify the array whenever it wants. By contrast, if an array were passed by reference in a language like Pascal which supports such things, the called method could do whatever it wanted with the array, but could not store the reference in such a way as to allow code to modify the array after it returned.
              – supercat
              Jan 10 '14 at 17:04










            • Indeed, in Pascal you can get the address of every variable, be it passed-by-reference or locally copied, addr does it untyped,@ does it with type, and you can modify the referenced variable later (except locally copied ones). But I don't see the point why you would do that. That slip of paper in your example (Object #24601) is a reference,its purpose is to help find the array in memory, it does not contain any array data in itself. If you restart your program, the same array might get a different object-id even if its content will be the same as it has been in the previous run.
              – karatedog
              Jan 10 '14 at 22:48










            • I'd thought the "@" operator was not part of standard Pascal, but was implemented as a common extension. Is it part of the standard? My point was that in a language with true pass-by-ref, and no ability to construct a non-ephemeral pointer to an ephemeral object, code which holds the only reference to an array, anywhere in the universe, before passing the array by reference can know that unless the recipient "cheats" it will still hold the only reference afterward. The only safe way to accomplish that in Java would be to construct a temporary object...
              – supercat
              Jan 10 '14 at 22:52










            • ...which encapsulates an AtomicReference and neither exposes the reference nor its target, but instead includes methods to do things to the target; once the code to which the object was passed returns, the AtomicReference [to which its creator kept a direct reference] should be invalidated and abandoned. That would provide the proper semantics, but it would be slow and icky.
              – supercat
              Jan 10 '14 at 22:54
















            In a language with pass-by-reference, the thing which is passed (the reference) is ephemeral; the recipient is not "supposed" to copy it. In Java, passing an array is passed is an "object identifier"--equivalent to a slip of paper which says "Object #24601", when the 24601st object constructed was an array. The recipient can copy "Object #24601" anywhere it wants, and anyone with a slip of paper saying "Object #24601" can do anything it wants with any of the array elements. The pattern of bits that is passed wouldn't actually say "Object #24601", of course, but...
            – supercat
            Jan 10 '14 at 17:02




            In a language with pass-by-reference, the thing which is passed (the reference) is ephemeral; the recipient is not "supposed" to copy it. In Java, passing an array is passed is an "object identifier"--equivalent to a slip of paper which says "Object #24601", when the 24601st object constructed was an array. The recipient can copy "Object #24601" anywhere it wants, and anyone with a slip of paper saying "Object #24601" can do anything it wants with any of the array elements. The pattern of bits that is passed wouldn't actually say "Object #24601", of course, but...
            – supercat
            Jan 10 '14 at 17:02












            ...the key point is that the recipient of the object-id that identifies the array can store that object-id wherever it wants and give it to whomever it wants, and any recipient would be able to access or modify the array whenever it wants. By contrast, if an array were passed by reference in a language like Pascal which supports such things, the called method could do whatever it wanted with the array, but could not store the reference in such a way as to allow code to modify the array after it returned.
            – supercat
            Jan 10 '14 at 17:04




            ...the key point is that the recipient of the object-id that identifies the array can store that object-id wherever it wants and give it to whomever it wants, and any recipient would be able to access or modify the array whenever it wants. By contrast, if an array were passed by reference in a language like Pascal which supports such things, the called method could do whatever it wanted with the array, but could not store the reference in such a way as to allow code to modify the array after it returned.
            – supercat
            Jan 10 '14 at 17:04












            Indeed, in Pascal you can get the address of every variable, be it passed-by-reference or locally copied, addr does it untyped,@ does it with type, and you can modify the referenced variable later (except locally copied ones). But I don't see the point why you would do that. That slip of paper in your example (Object #24601) is a reference,its purpose is to help find the array in memory, it does not contain any array data in itself. If you restart your program, the same array might get a different object-id even if its content will be the same as it has been in the previous run.
            – karatedog
            Jan 10 '14 at 22:48




            Indeed, in Pascal you can get the address of every variable, be it passed-by-reference or locally copied, addr does it untyped,@ does it with type, and you can modify the referenced variable later (except locally copied ones). But I don't see the point why you would do that. That slip of paper in your example (Object #24601) is a reference,its purpose is to help find the array in memory, it does not contain any array data in itself. If you restart your program, the same array might get a different object-id even if its content will be the same as it has been in the previous run.
            – karatedog
            Jan 10 '14 at 22:48












            I'd thought the "@" operator was not part of standard Pascal, but was implemented as a common extension. Is it part of the standard? My point was that in a language with true pass-by-ref, and no ability to construct a non-ephemeral pointer to an ephemeral object, code which holds the only reference to an array, anywhere in the universe, before passing the array by reference can know that unless the recipient "cheats" it will still hold the only reference afterward. The only safe way to accomplish that in Java would be to construct a temporary object...
            – supercat
            Jan 10 '14 at 22:52




            I'd thought the "@" operator was not part of standard Pascal, but was implemented as a common extension. Is it part of the standard? My point was that in a language with true pass-by-ref, and no ability to construct a non-ephemeral pointer to an ephemeral object, code which holds the only reference to an array, anywhere in the universe, before passing the array by reference can know that unless the recipient "cheats" it will still hold the only reference afterward. The only safe way to accomplish that in Java would be to construct a temporary object...
            – supercat
            Jan 10 '14 at 22:52












            ...which encapsulates an AtomicReference and neither exposes the reference nor its target, but instead includes methods to do things to the target; once the code to which the object was passed returns, the AtomicReference [to which its creator kept a direct reference] should be invalidated and abandoned. That would provide the proper semantics, but it would be slow and icky.
            – supercat
            Jan 10 '14 at 22:54




            ...which encapsulates an AtomicReference and neither exposes the reference nor its target, but instead includes methods to do things to the target; once the code to which the object was passed returns, the AtomicReference [to which its creator kept a direct reference] should be invalidated and abandoned. That would provide the proper semantics, but it would be slow and icky.
            – supercat
            Jan 10 '14 at 22:54










            up vote
            64
            down vote













            Java is always pass by value, not pass by reference



            First of all, we need to understand what pass by value and pass by reference are.



            Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.



            Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.



            Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:



            public class PassByValue {
            public static void main(String args) {
            Test t = new Test();
            t.name = "initialvalue";
            new PassByValue().changeValue(t);
            System.out.println(t.name);
            }

            public void changeValue(Test f) {
            f.name = "changevalue";
            }
            }

            class Test {
            String name;
            }


            The output of this program is:




            changevalue



            Let's understand step by step:



            Test t = new Test();


            As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .



            first illustration



            new PassByValue().changeValue(t);


            When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.



            second illustration



            If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.



            To understand this more clearly, consider the following example:



            public class PassByValue {
            public static void main(String args) {
            Test t = new Test();
            t.name = "initialvalue";
            new PassByValue().changeRefence(t);
            System.out.println(t.name);
            }

            public void changeRefence(Test f) {
            f = null;
            }
            }

            class Test {
            String name;
            }


            Will this throw a NullPointerException? No, because it only passes a copy of the reference.
            In the case of passing by reference, it could have thrown a NullPointerException, as seen below:



            third illustration



            Hopefully this will help.





            share























            • Excellent answer, the key statement: "When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function"
              – pedram bashiri
              May 4 at 16:25















            up vote
            64
            down vote













            Java is always pass by value, not pass by reference



            First of all, we need to understand what pass by value and pass by reference are.



            Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.



            Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.



            Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:



            public class PassByValue {
            public static void main(String args) {
            Test t = new Test();
            t.name = "initialvalue";
            new PassByValue().changeValue(t);
            System.out.println(t.name);
            }

            public void changeValue(Test f) {
            f.name = "changevalue";
            }
            }

            class Test {
            String name;
            }


            The output of this program is:




            changevalue



            Let's understand step by step:



            Test t = new Test();


            As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .



            first illustration



            new PassByValue().changeValue(t);


            When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.



            second illustration



            If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.



            To understand this more clearly, consider the following example:



            public class PassByValue {
            public static void main(String args) {
            Test t = new Test();
            t.name = "initialvalue";
            new PassByValue().changeRefence(t);
            System.out.println(t.name);
            }

            public void changeRefence(Test f) {
            f = null;
            }
            }

            class Test {
            String name;
            }


            Will this throw a NullPointerException? No, because it only passes a copy of the reference.
            In the case of passing by reference, it could have thrown a NullPointerException, as seen below:



            third illustration



            Hopefully this will help.





            share























            • Excellent answer, the key statement: "When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function"
              – pedram bashiri
              May 4 at 16:25













            up vote
            64
            down vote










            up vote
            64
            down vote









            Java is always pass by value, not pass by reference



            First of all, we need to understand what pass by value and pass by reference are.



            Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.



            Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.



            Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:



            public class PassByValue {
            public static void main(String args) {
            Test t = new Test();
            t.name = "initialvalue";
            new PassByValue().changeValue(t);
            System.out.println(t.name);
            }

            public void changeValue(Test f) {
            f.name = "changevalue";
            }
            }

            class Test {
            String name;
            }


            The output of this program is:




            changevalue



            Let's understand step by step:



            Test t = new Test();


            As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .



            first illustration



            new PassByValue().changeValue(t);


            When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.



            second illustration



            If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.



            To understand this more clearly, consider the following example:



            public class PassByValue {
            public static void main(String args) {
            Test t = new Test();
            t.name = "initialvalue";
            new PassByValue().changeRefence(t);
            System.out.println(t.name);
            }

            public void changeRefence(Test f) {
            f = null;
            }
            }

            class Test {
            String name;
            }


            Will this throw a NullPointerException? No, because it only passes a copy of the reference.
            In the case of passing by reference, it could have thrown a NullPointerException, as seen below:



            third illustration



            Hopefully this will help.





            share














            Java is always pass by value, not pass by reference



            First of all, we need to understand what pass by value and pass by reference are.



            Pass by value means that you are making a copy in memory of the actual parameter's value that is passed in. This is a copy of the contents of the actual parameter.



            Pass by reference (also called pass by address) means that a copy of the address of the actual parameter is stored.



            Sometimes Java can give the illusion of pass by reference. Let's see how it works by using the example below:



            public class PassByValue {
            public static void main(String args) {
            Test t = new Test();
            t.name = "initialvalue";
            new PassByValue().changeValue(t);
            System.out.println(t.name);
            }

            public void changeValue(Test f) {
            f.name = "changevalue";
            }
            }

            class Test {
            String name;
            }


            The output of this program is:




            changevalue



            Let's understand step by step:



            Test t = new Test();


            As we all know it will create an object in the heap and return the reference value back to t. For example, suppose the value of t is 0x100234 (we don't know the actual JVM internal value, this is just an example) .



            first illustration



            new PassByValue().changeValue(t);


            When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function. Since it is passing by value, it passes a copy of the variable rather than the actual reference of it. Since we said the value of t was 0x100234, both t and f will have the same value and hence they will point to the same object.



            second illustration



            If you change anything in the function using reference f it will modify the existing contents of the object. That is why we got the output changevalue, which is updated in the function.



            To understand this more clearly, consider the following example:



            public class PassByValue {
            public static void main(String args) {
            Test t = new Test();
            t.name = "initialvalue";
            new PassByValue().changeRefence(t);
            System.out.println(t.name);
            }

            public void changeRefence(Test f) {
            f = null;
            }
            }

            class Test {
            String name;
            }


            Will this throw a NullPointerException? No, because it only passes a copy of the reference.
            In the case of passing by reference, it could have thrown a NullPointerException, as seen below:



            third illustration



            Hopefully this will help.






            share













            share


            share








            edited Apr 17 at 12:57


























            community wiki





            4 revs, 3 users 80%
            Ganesh













            • Excellent answer, the key statement: "When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function"
              – pedram bashiri
              May 4 at 16:25


















            • Excellent answer, the key statement: "When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function"
              – pedram bashiri
              May 4 at 16:25
















            Excellent answer, the key statement: "When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function"
            – pedram bashiri
            May 4 at 16:25




            Excellent answer, the key statement: "When passing reference t to the function it will not directly pass the actual reference value of object test, but it will create a copy of t and then pass it to the function"
            – pedram bashiri
            May 4 at 16:25










            up vote
            50
            down vote













            As far as I know, Java only knows call by value. This means for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects. However I think there are some pitfalls; for example, this will not work:



            public static void swap(StringBuffer s1, StringBuffer s2) {
            StringBuffer temp = s1;
            s1 = s2;
            s2 = temp;
            }


            public static void main(String args) {
            StringBuffer s1 = new StringBuffer("Hello");
            StringBuffer s2 = new StringBuffer("World");
            swap(s1, s2);
            System.out.println(s1);
            System.out.println(s2);
            }


            This will populate Hello World and not World Hello because in the swap function you use copys which have no impact on the references in the main. But if your objects are not immutable you can change it for example:



            public static void appendWorld(StringBuffer s1) {
            s1.append(" World");
            }

            public static void main(String args) {
            StringBuffer s = new StringBuffer("Hello");
            appendWorld(s);
            System.out.println(s);
            }


            This will populate Hello World on the command line. If you change StringBuffer into String it will produce just Hello because String is immutable. For example:



            public static void appendWorld(String s){
            s = s+" World";
            }

            public static void main(String args) {
            String s = new String("Hello");
            appendWorld(s);
            System.out.println(s);
            }


            However you could make a wrapper for String like this which would make it able to use it with Strings:



            class StringWrapper {
            public String value;

            public StringWrapper(String value) {
            this.value = value;
            }
            }

            public static void appendWorld(StringWrapper s){
            s.value = s.value +" World";
            }

            public static void main(String args) {
            StringWrapper s = new StringWrapper("Hello");
            appendWorld(s);
            System.out.println(s.value);
            }


            edit: i believe this is also the reason to use StringBuffer when it comes to "adding" two Strings because you can modifie the original object which u can't with immutable objects like String is.





            share























            • +1 for the swap test -- probably the most straightforward and relatable way to distinguish between passing by reference and passing a reference by value. Iff you can easily write a function swap(a, b) that (1) swaps a and b from the caller's POV, (2) is type-agnostic to the extent that static typing allows (meaning using it with another type requires nothing more than changing the declared types of a and b), and (3) doesn't require the caller to explicitly pass a pointer or name, then the language supports passing by reference.
              – cHao
              Dec 17 '13 at 21:24










            • "..for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects" - perfectly written!
              – Raúl
              Nov 24 '16 at 13:16















            up vote
            50
            down vote













            As far as I know, Java only knows call by value. This means for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects. However I think there are some pitfalls; for example, this will not work:



            public static void swap(StringBuffer s1, StringBuffer s2) {
            StringBuffer temp = s1;
            s1 = s2;
            s2 = temp;
            }


            public static void main(String args) {
            StringBuffer s1 = new StringBuffer("Hello");
            StringBuffer s2 = new StringBuffer("World");
            swap(s1, s2);
            System.out.println(s1);
            System.out.println(s2);
            }


            This will populate Hello World and not World Hello because in the swap function you use copys which have no impact on the references in the main. But if your objects are not immutable you can change it for example:



            public static void appendWorld(StringBuffer s1) {
            s1.append(" World");
            }

            public static void main(String args) {
            StringBuffer s = new StringBuffer("Hello");
            appendWorld(s);
            System.out.println(s);
            }


            This will populate Hello World on the command line. If you change StringBuffer into String it will produce just Hello because String is immutable. For example:



            public static void appendWorld(String s){
            s = s+" World";
            }

            public static void main(String args) {
            String s = new String("Hello");
            appendWorld(s);
            System.out.println(s);
            }


            However you could make a wrapper for String like this which would make it able to use it with Strings:



            class StringWrapper {
            public String value;

            public StringWrapper(String value) {
            this.value = value;
            }
            }

            public static void appendWorld(StringWrapper s){
            s.value = s.value +" World";
            }

            public static void main(String args) {
            StringWrapper s = new StringWrapper("Hello");
            appendWorld(s);
            System.out.println(s.value);
            }


            edit: i believe this is also the reason to use StringBuffer when it comes to "adding" two Strings because you can modifie the original object which u can't with immutable objects like String is.





            share























            • +1 for the swap test -- probably the most straightforward and relatable way to distinguish between passing by reference and passing a reference by value. Iff you can easily write a function swap(a, b) that (1) swaps a and b from the caller's POV, (2) is type-agnostic to the extent that static typing allows (meaning using it with another type requires nothing more than changing the declared types of a and b), and (3) doesn't require the caller to explicitly pass a pointer or name, then the language supports passing by reference.
              – cHao
              Dec 17 '13 at 21:24










            • "..for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects" - perfectly written!
              – Raúl
              Nov 24 '16 at 13:16













            up vote
            50
            down vote










            up vote
            50
            down vote









            As far as I know, Java only knows call by value. This means for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects. However I think there are some pitfalls; for example, this will not work:



            public static void swap(StringBuffer s1, StringBuffer s2) {
            StringBuffer temp = s1;
            s1 = s2;
            s2 = temp;
            }


            public static void main(String args) {
            StringBuffer s1 = new StringBuffer("Hello");
            StringBuffer s2 = new StringBuffer("World");
            swap(s1, s2);
            System.out.println(s1);
            System.out.println(s2);
            }


            This will populate Hello World and not World Hello because in the swap function you use copys which have no impact on the references in the main. But if your objects are not immutable you can change it for example:



            public static void appendWorld(StringBuffer s1) {
            s1.append(" World");
            }

            public static void main(String args) {
            StringBuffer s = new StringBuffer("Hello");
            appendWorld(s);
            System.out.println(s);
            }


            This will populate Hello World on the command line. If you change StringBuffer into String it will produce just Hello because String is immutable. For example:



            public static void appendWorld(String s){
            s = s+" World";
            }

            public static void main(String args) {
            String s = new String("Hello");
            appendWorld(s);
            System.out.println(s);
            }


            However you could make a wrapper for String like this which would make it able to use it with Strings:



            class StringWrapper {
            public String value;

            public StringWrapper(String value) {
            this.value = value;
            }
            }

            public static void appendWorld(StringWrapper s){
            s.value = s.value +" World";
            }

            public static void main(String args) {
            StringWrapper s = new StringWrapper("Hello");
            appendWorld(s);
            System.out.println(s.value);
            }


            edit: i believe this is also the reason to use StringBuffer when it comes to "adding" two Strings because you can modifie the original object which u can't with immutable objects like String is.





            share














            As far as I know, Java only knows call by value. This means for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects. However I think there are some pitfalls; for example, this will not work:



            public static void swap(StringBuffer s1, StringBuffer s2) {
            StringBuffer temp = s1;
            s1 = s2;
            s2 = temp;
            }


            public static void main(String args) {
            StringBuffer s1 = new StringBuffer("Hello");
            StringBuffer s2 = new StringBuffer("World");
            swap(s1, s2);
            System.out.println(s1);
            System.out.println(s2);
            }


            This will populate Hello World and not World Hello because in the swap function you use copys which have no impact on the references in the main. But if your objects are not immutable you can change it for example:



            public static void appendWorld(StringBuffer s1) {
            s1.append(" World");
            }

            public static void main(String args) {
            StringBuffer s = new StringBuffer("Hello");
            appendWorld(s);
            System.out.println(s);
            }


            This will populate Hello World on the command line. If you change StringBuffer into String it will produce just Hello because String is immutable. For example:



            public static void appendWorld(String s){
            s = s+" World";
            }

            public static void main(String args) {
            String s = new String("Hello");
            appendWorld(s);
            System.out.println(s);
            }


            However you could make a wrapper for String like this which would make it able to use it with Strings:



            class StringWrapper {
            public String value;

            public StringWrapper(String value) {
            this.value = value;
            }
            }

            public static void appendWorld(StringWrapper s){
            s.value = s.value +" World";
            }

            public static void main(String args) {
            StringWrapper s = new StringWrapper("Hello");
            appendWorld(s);
            System.out.println(s.value);
            }


            edit: i believe this is also the reason to use StringBuffer when it comes to "adding" two Strings because you can modifie the original object which u can't with immutable objects like String is.






            share













            share


            share








            edited Apr 2 '09 at 17:58


























            community wiki





            4 revs, 2 users 76%
            kukudas














            • +1 for the swap test -- probably the most straightforward and relatable way to distinguish between passing by reference and passing a reference by value. Iff you can easily write a function swap(a, b) that (1) swaps a and b from the caller's POV, (2) is type-agnostic to the extent that static typing allows (meaning using it with another type requires nothing more than changing the declared types of a and b), and (3) doesn't require the caller to explicitly pass a pointer or name, then the language supports passing by reference.
              – cHao
              Dec 17 '13 at 21:24










            • "..for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects" - perfectly written!
              – Raúl
              Nov 24 '16 at 13:16


















            • +1 for the swap test -- probably the most straightforward and relatable way to distinguish between passing by reference and passing a reference by value. Iff you can easily write a function swap(a, b) that (1) swaps a and b from the caller's POV, (2) is type-agnostic to the extent that static typing allows (meaning using it with another type requires nothing more than changing the declared types of a and b), and (3) doesn't require the caller to explicitly pass a pointer or name, then the language supports passing by reference.
              – cHao
              Dec 17 '13 at 21:24










            • "..for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects" - perfectly written!
              – Raúl
              Nov 24 '16 at 13:16
















            +1 for the swap test -- probably the most straightforward and relatable way to distinguish between passing by reference and passing a reference by value. Iff you can easily write a function swap(a, b) that (1) swaps a and b from the caller's POV, (2) is type-agnostic to the extent that static typing allows (meaning using it with another type requires nothing more than changing the declared types of a and b), and (3) doesn't require the caller to explicitly pass a pointer or name, then the language supports passing by reference.
            – cHao
            Dec 17 '13 at 21:24




            +1 for the swap test -- probably the most straightforward and relatable way to distinguish between passing by reference and passing a reference by value. Iff you can easily write a function swap(a, b) that (1) swaps a and b from the caller's POV, (2) is type-agnostic to the extent that static typing allows (meaning using it with another type requires nothing more than changing the declared types of a and b), and (3) doesn't require the caller to explicitly pass a pointer or name, then the language supports passing by reference.
            – cHao
            Dec 17 '13 at 21:24












            "..for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects" - perfectly written!
            – Raúl
            Nov 24 '16 at 13:16




            "..for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects" - perfectly written!
            – Raúl
            Nov 24 '16 at 13:16










            up vote
            50
            down vote













            No, it's not pass by reference.



            Java is pass by value according to 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.






            share



























              up vote
              50
              down vote













              No, it's not pass by reference.



              Java is pass by value according to 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.






              share

























                up vote
                50
                down vote










                up vote
                50
                down vote









                No, it's not pass by reference.



                Java is pass by value according to 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.






                share














                No, it's not pass by reference.



                Java is pass by value according to 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.







                share













                share


                share








                edited Aug 22 '15 at 5:50


























                community wiki





                3 revs, 3 users 82%
                rorrohprog























                    up vote
                    46
                    down vote













                    Let me try to explain my understanding with the help of four examples. Java is pass-by-value, and not pass-by-reference



                    /**



                    Pass By Value



                    In Java, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.



                    */



                    Example 1:



                    public class PassByValueString {
                    public static void main(String args) {
                    new PassByValueString().caller();
                    }

                    public void caller() {
                    String value = "Nikhil";
                    boolean valueflag = false;
                    String output = method(value, valueflag);
                    /*
                    * 'output' is insignificant in this example. we are more interested in
                    * 'value' and 'valueflag'
                    */
                    System.out.println("output : " + output);
                    System.out.println("value : " + value);
                    System.out.println("valueflag : " + valueflag);

                    }

                    public String method(String value, boolean valueflag) {
                    value = "Anand";
                    valueflag = true;
                    return "output";
                    }
                    }


                    Result



                    output : output
                    value : Nikhil
                    valueflag : false


                    Example 2:



                    /**
                    *
                    * Pass By Value
                    *
                    */



                    public class PassByValueNewString {
                    public static void main(String args) {
                    new PassByValueNewString().caller();
                    }

                    public void caller() {
                    String value = new String("Nikhil");
                    boolean valueflag = false;
                    String output = method(value, valueflag);
                    /*
                    * 'output' is insignificant in this example. we are more interested in
                    * 'value' and 'valueflag'
                    */
                    System.out.println("output : " + output);
                    System.out.println("value : " + value);
                    System.out.println("valueflag : " + valueflag);

                    }

                    public String method(String value, boolean valueflag) {
                    value = "Anand";
                    valueflag = true;
                    return "output";
                    }
                    }


                    Result



                    output : output
                    value : Nikhil
                    valueflag : false


                    Example 3:



                    /**
                    This 'Pass By Value has a feeling of 'Pass By Reference'



                    Some people say primitive types and 'String' are 'pass by value'
                    and objects are 'pass by reference'.



                    But from this example, we can understand that it is infact pass by value only,
                    keeping in mind that here we are passing the reference as the value.
                    ie: reference is passed by value.
                    That's why are able to change and still it holds true after the local scope.
                    But we cannot change the actual reference outside the original scope.
                    what that means is demonstrated by next example of PassByValueObjectCase2.



                    */



                    public class PassByValueObjectCase1 {

                    private class Student {
                    int id;
                    String name;
                    public Student() {
                    }
                    public Student(int id, String name) {
                    super();
                    this.id = id;
                    this.name = name;
                    }
                    public int getId() {
                    return id;
                    }
                    public void setId(int id) {
                    this.id = id;
                    }
                    public String getName() {
                    return name;
                    }
                    public void setName(String name) {
                    this.name = name;
                    }
                    @Override
                    public String toString() {
                    return "Student [id=" + id + ", name=" + name + "]";
                    }
                    }

                    public static void main(String args) {
                    new PassByValueObjectCase1().caller();
                    }

                    public void caller() {
                    Student student = new Student(10, "Nikhil");
                    String output = method(student);
                    /*
                    * 'output' is insignificant in this example. we are more interested in
                    * 'student'
                    */
                    System.out.println("output : " + output);
                    System.out.println("student : " + student);
                    }

                    public String method(Student student) {
                    student.setName("Anand");
                    return "output";
                    }
                    }


                    Result



                    output : output
                    student : Student [id=10, name=Anand]


                    Example 4:



                    /**



                    In addition to what was mentioned in Example3 (PassByValueObjectCase1.java), we cannot change the actual reference outside the original scope."



                    Note: I am not pasting the code for private class Student. The class definition for Student is same as Example3.



                    */



                    public class PassByValueObjectCase2 {

                    public static void main(String args) {
                    new PassByValueObjectCase2().caller();
                    }

                    public void caller() {
                    // student has the actual reference to a Student object created
                    // can we change this actual reference outside the local scope? Let's see
                    Student student = new Student(10, "Nikhil");
                    String output = method(student);
                    /*
                    * 'output' is insignificant in this example. we are more interested in
                    * 'student'
                    */
                    System.out.println("output : " + output);
                    System.out.println("student : " + student); // Will it print Nikhil or Anand?
                    }

                    public String method(Student student) {
                    student = new Student(20, "Anand");
                    return "output";
                    }

                    }


                    Result



                    output : output
                    student : Student [id=10, name=Nikhil]




                    share



























                      up vote
                      46
                      down vote













                      Let me try to explain my understanding with the help of four examples. Java is pass-by-value, and not pass-by-reference



                      /**



                      Pass By Value



                      In Java, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.



                      */



                      Example 1:



                      public class PassByValueString {
                      public static void main(String args) {
                      new PassByValueString().caller();
                      }

                      public void caller() {
                      String value = "Nikhil";
                      boolean valueflag = false;
                      String output = method(value, valueflag);
                      /*
                      * 'output' is insignificant in this example. we are more interested in
                      * 'value' and 'valueflag'
                      */
                      System.out.println("output : " + output);
                      System.out.println("value : " + value);
                      System.out.println("valueflag : " + valueflag);

                      }

                      public String method(String value, boolean valueflag) {
                      value = "Anand";
                      valueflag = true;
                      return "output";
                      }
                      }


                      Result



                      output : output
                      value : Nikhil
                      valueflag : false


                      Example 2:



                      /**
                      *
                      * Pass By Value
                      *
                      */



                      public class PassByValueNewString {
                      public static void main(String args) {
                      new PassByValueNewString().caller();
                      }

                      public void caller() {
                      String value = new String("Nikhil");
                      boolean valueflag = false;
                      String output = method(value, valueflag);
                      /*
                      * 'output' is insignificant in this example. we are more interested in
                      * 'value' and 'valueflag'
                      */
                      System.out.println("output : " + output);
                      System.out.println("value : " + value);
                      System.out.println("valueflag : " + valueflag);

                      }

                      public String method(String value, boolean valueflag) {
                      value = "Anand";
                      valueflag = true;
                      return "output";
                      }
                      }


                      Result



                      output : output
                      value : Nikhil
                      valueflag : false


                      Example 3:



                      /**
                      This 'Pass By Value has a feeling of 'Pass By Reference'



                      Some people say primitive types and 'String' are 'pass by value'
                      and objects are 'pass by reference'.



                      But from this example, we can understand that it is infact pass by value only,
                      keeping in mind that here we are passing the reference as the value.
                      ie: reference is passed by value.
                      That's why are able to change and still it holds true after the local scope.
                      But we cannot change the actual reference outside the original scope.
                      what that means is demonstrated by next example of PassByValueObjectCase2.



                      */



                      public class PassByValueObjectCase1 {

                      private class Student {
                      int id;
                      String name;
                      public Student() {
                      }
                      public Student(int id, String name) {
                      super();
                      this.id = id;
                      this.name = name;
                      }
                      public int getId() {
                      return id;
                      }
                      public void setId(int id) {
                      this.id = id;
                      }
                      public String getName() {
                      return name;
                      }
                      public void setName(String name) {
                      this.name = name;
                      }
                      @Override
                      public String toString() {
                      return "Student [id=" + id + ", name=" + name + "]";
                      }
                      }

                      public static void main(String args) {
                      new PassByValueObjectCase1().caller();
                      }

                      public void caller() {
                      Student student = new Student(10, "Nikhil");
                      String output = method(student);
                      /*
                      * 'output' is insignificant in this example. we are more interested in
                      * 'student'
                      */
                      System.out.println("output : " + output);
                      System.out.println("student : " + student);
                      }

                      public String method(Student student) {
                      student.setName("Anand");
                      return "output";
                      }
                      }


                      Result



                      output : output
                      student : Student [id=10, name=Anand]


                      Example 4:



                      /**



                      In addition to what was mentioned in Example3 (PassByValueObjectCase1.java), we cannot change the actual reference outside the original scope."



                      Note: I am not pasting the code for private class Student. The class definition for Student is same as Example3.



                      */



                      public class PassByValueObjectCase2 {

                      public static void main(String args) {
                      new PassByValueObjectCase2().caller();
                      }

                      public void caller() {
                      // student has the actual reference to a Student object created
                      // can we change this actual reference outside the local scope? Let's see
                      Student student = new Student(10, "Nikhil");
                      String output = method(student);
                      /*
                      * 'output' is insignificant in this example. we are more interested in
                      * 'student'
                      */
                      System.out.println("output : " + output);
                      System.out.println("student : " + student); // Will it print Nikhil or Anand?
                      }

                      public String method(Student student) {
                      student = new Student(20, "Anand");
                      return "output";
                      }

                      }


                      Result



                      output : output
                      student : Student [id=10, name=Nikhil]




                      share

























                        up vote
                        46
                        down vote










                        up vote
                        46
                        down vote









                        Let me try to explain my understanding with the help of four examples. Java is pass-by-value, and not pass-by-reference



                        /**



                        Pass By Value



                        In Java, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.



                        */



                        Example 1:



                        public class PassByValueString {
                        public static void main(String args) {
                        new PassByValueString().caller();
                        }

                        public void caller() {
                        String value = "Nikhil";
                        boolean valueflag = false;
                        String output = method(value, valueflag);
                        /*
                        * 'output' is insignificant in this example. we are more interested in
                        * 'value' and 'valueflag'
                        */
                        System.out.println("output : " + output);
                        System.out.println("value : " + value);
                        System.out.println("valueflag : " + valueflag);

                        }

                        public String method(String value, boolean valueflag) {
                        value = "Anand";
                        valueflag = true;
                        return "output";
                        }
                        }


                        Result



                        output : output
                        value : Nikhil
                        valueflag : false


                        Example 2:



                        /**
                        *
                        * Pass By Value
                        *
                        */



                        public class PassByValueNewString {
                        public static void main(String args) {
                        new PassByValueNewString().caller();
                        }

                        public void caller() {
                        String value = new String("Nikhil");
                        boolean valueflag = false;
                        String output = method(value, valueflag);
                        /*
                        * 'output' is insignificant in this example. we are more interested in
                        * 'value' and 'valueflag'
                        */
                        System.out.println("output : " + output);
                        System.out.println("value : " + value);
                        System.out.println("valueflag : " + valueflag);

                        }

                        public String method(String value, boolean valueflag) {
                        value = "Anand";
                        valueflag = true;
                        return "output";
                        }
                        }


                        Result



                        output : output
                        value : Nikhil
                        valueflag : false


                        Example 3:



                        /**
                        This 'Pass By Value has a feeling of 'Pass By Reference'



                        Some people say primitive types and 'String' are 'pass by value'
                        and objects are 'pass by reference'.



                        But from this example, we can understand that it is infact pass by value only,
                        keeping in mind that here we are passing the reference as the value.
                        ie: reference is passed by value.
                        That's why are able to change and still it holds true after the local scope.
                        But we cannot change the actual reference outside the original scope.
                        what that means is demonstrated by next example of PassByValueObjectCase2.



                        */



                        public class PassByValueObjectCase1 {

                        private class Student {
                        int id;
                        String name;
                        public Student() {
                        }
                        public Student(int id, String name) {
                        super();
                        this.id = id;
                        this.name = name;
                        }
                        public int getId() {
                        return id;
                        }
                        public void setId(int id) {
                        this.id = id;
                        }
                        public String getName() {
                        return name;
                        }
                        public void setName(String name) {
                        this.name = name;
                        }
                        @Override
                        public String toString() {
                        return "Student [id=" + id + ", name=" + name + "]";
                        }
                        }

                        public static void main(String args) {
                        new PassByValueObjectCase1().caller();
                        }

                        public void caller() {
                        Student student = new Student(10, "Nikhil");
                        String output = method(student);
                        /*
                        * 'output' is insignificant in this example. we are more interested in
                        * 'student'
                        */
                        System.out.println("output : " + output);
                        System.out.println("student : " + student);
                        }

                        public String method(Student student) {
                        student.setName("Anand");
                        return "output";
                        }
                        }


                        Result



                        output : output
                        student : Student [id=10, name=Anand]


                        Example 4:



                        /**



                        In addition to what was mentioned in Example3 (PassByValueObjectCase1.java), we cannot change the actual reference outside the original scope."



                        Note: I am not pasting the code for private class Student. The class definition for Student is same as Example3.



                        */



                        public class PassByValueObjectCase2 {

                        public static void main(String args) {
                        new PassByValueObjectCase2().caller();
                        }

                        public void caller() {
                        // student has the actual reference to a Student object created
                        // can we change this actual reference outside the local scope? Let's see
                        Student student = new Student(10, "Nikhil");
                        String output = method(student);
                        /*
                        * 'output' is insignificant in this example. we are more interested in
                        * 'student'
                        */
                        System.out.println("output : " + output);
                        System.out.println("student : " + student); // Will it print Nikhil or Anand?
                        }

                        public String method(Student student) {
                        student = new Student(20, "Anand");
                        return "output";
                        }

                        }


                        Result



                        output : output
                        student : Student [id=10, name=Nikhil]




                        share














                        Let me try to explain my understanding with the help of four examples. Java is pass-by-value, and not pass-by-reference



                        /**



                        Pass By Value



                        In Java, all parameters are passed by value, i.e. assigning a method argument is not visible to the caller.



                        */



                        Example 1:



                        public class PassByValueString {
                        public static void main(String args) {
                        new PassByValueString().caller();
                        }

                        public void caller() {
                        String value = "Nikhil";
                        boolean valueflag = false;
                        String output = method(value, valueflag);
                        /*
                        * 'output' is insignificant in this example. we are more interested in
                        * 'value' and 'valueflag'
                        */
                        System.out.println("output : " + output);
                        System.out.println("value : " + value);
                        System.out.println("valueflag : " + valueflag);

                        }

                        public String method(String value, boolean valueflag) {
                        value = "Anand";
                        valueflag = true;
                        return "output";
                        }
                        }


                        Result



                        output : output
                        value : Nikhil
                        valueflag : false


                        Example 2:



                        /**
                        *
                        * Pass By Value
                        *
                        */



                        public class PassByValueNewString {
                        public static void main(String args) {
                        new PassByValueNewString().caller();
                        }

                        public void caller() {
                        String value = new String("Nikhil");
                        boolean valueflag = false;
                        String output = method(value, valueflag);
                        /*
                        * 'output' is insignificant in this example. we are more interested in
                        * 'value' and 'valueflag'
                        */
                        System.out.println("output : " + output);
                        System.out.println("value : " + value);
                        System.out.println("valueflag : " + valueflag);

                        }

                        public String method(String value, boolean valueflag) {
                        value = "Anand";
                        valueflag = true;
                        return "output";
                        }
                        }


                        Result



                        output : output
                        value : Nikhil
                        valueflag : false


                        Example 3:



                        /**
                        This 'Pass By Value has a feeling of 'Pass By Reference'



                        Some people say primitive types and 'String' are 'pass by value'
                        and objects are 'pass by reference'.



                        But from this example, we can understand that it is infact pass by value only,
                        keeping in mind that here we are passing the reference as the value.
                        ie: reference is passed by value.
                        That's why are able to change and still it holds true after the local scope.
                        But we cannot change the actual reference outside the original scope.
                        what that means is demonstrated by next example of PassByValueObjectCase2.



                        */



                        public class PassByValueObjectCase1 {

                        private class Student {
                        int id;
                        String name;
                        public Student() {
                        }
                        public Student(int id, String name) {
                        super();
                        this.id = id;
                        this.name = name;
                        }
                        public int getId() {
                        return id;
                        }
                        public void setId(int id) {
                        this.id = id;
                        }
                        public String getName() {
                        return name;
                        }
                        public void setName(String name) {
                        this.name = name;
                        }
                        @Override
                        public String toString() {
                        return "Student [id=" + id + ", name=" + name + "]";
                        }
                        }

                        public static void main(String args) {
                        new PassByValueObjectCase1().caller();
                        }

                        public void caller() {
                        Student student = new Student(10, "Nikhil");
                        String output = method(student);
                        /*
                        * 'output' is insignificant in this example. we are more interested in
                        * 'student'
                        */
                        System.out.println("output : " + output);
                        System.out.println("student : " + student);
                        }

                        public String method(Student student) {
                        student.setName("Anand");
                        return "output";
                        }
                        }


                        Result



                        output : output
                        student : Student [id=10, name=Anand]


                        Example 4:



                        /**



                        In addition to what was mentioned in Example3 (PassByValueObjectCase1.java), we cannot change the actual reference outside the original scope."



                        Note: I am not pasting the code for private class Student. The class definition for Student is same as Example3.



                        */



                        public class PassByValueObjectCase2 {

                        public static void main(String args) {
                        new PassByValueObjectCase2().caller();
                        }

                        public void caller() {
                        // student has the actual reference to a Student object created
                        // can we change this actual reference outside the local scope? Let's see
                        Student student = new Student(10, "Nikhil");
                        String output = method(student);
                        /*
                        * 'output' is insignificant in this example. we are more interested in
                        * 'student'
                        */
                        System.out.println("output : " + output);
                        System.out.println("student : " + student); // Will it print Nikhil or Anand?
                        }

                        public String method(Student student) {
                        student = new Student(20, "Anand");
                        return "output";
                        }

                        }


                        Result



                        output : output
                        student : Student [id=10, name=Nikhil]





                        share













                        share


                        share








                        edited May 12 '15 at 21:30


























                        community wiki





                        2 revs
                        spiderman























                            up vote
                            44
                            down vote













                            You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:



                            void getValues(int& arg1, int& arg2) {
                            arg1 = 1;
                            arg2 = 2;
                            }
                            void caller() {
                            int x;
                            int y;
                            getValues(x, y);
                            cout << "Result: " << x << " " << y << endl;
                            }


                            Sometimes you want to use the same pattern in Java, but you can't; at least not directly. Instead you could do something like this:



                            void getValues(int arg1, int arg2) {
                            arg1[0] = 1;
                            arg2[0] = 2;
                            }
                            void caller() {
                            int x = new int[1];
                            int y = new int[1];
                            getValues(x, y);
                            System.out.println("Result: " + x[0] + " " + y[0]);
                            }


                            As was explained in previous answers, in Java you're passing a pointer to the array as a value into getValues. That is enough, because the method then modifies the array element, and by convention you're expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn't necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.





                            share



























                              up vote
                              44
                              down vote













                              You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:



                              void getValues(int& arg1, int& arg2) {
                              arg1 = 1;
                              arg2 = 2;
                              }
                              void caller() {
                              int x;
                              int y;
                              getValues(x, y);
                              cout << "Result: " << x << " " << y << endl;
                              }


                              Sometimes you want to use the same pattern in Java, but you can't; at least not directly. Instead you could do something like this:



                              void getValues(int arg1, int arg2) {
                              arg1[0] = 1;
                              arg2[0] = 2;
                              }
                              void caller() {
                              int x = new int[1];
                              int y = new int[1];
                              getValues(x, y);
                              System.out.println("Result: " + x[0] + " " + y[0]);
                              }


                              As was explained in previous answers, in Java you're passing a pointer to the array as a value into getValues. That is enough, because the method then modifies the array element, and by convention you're expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn't necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.





                              share

























                                up vote
                                44
                                down vote










                                up vote
                                44
                                down vote









                                You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:



                                void getValues(int& arg1, int& arg2) {
                                arg1 = 1;
                                arg2 = 2;
                                }
                                void caller() {
                                int x;
                                int y;
                                getValues(x, y);
                                cout << "Result: " << x << " " << y << endl;
                                }


                                Sometimes you want to use the same pattern in Java, but you can't; at least not directly. Instead you could do something like this:



                                void getValues(int arg1, int arg2) {
                                arg1[0] = 1;
                                arg2[0] = 2;
                                }
                                void caller() {
                                int x = new int[1];
                                int y = new int[1];
                                getValues(x, y);
                                System.out.println("Result: " + x[0] + " " + y[0]);
                                }


                                As was explained in previous answers, in Java you're passing a pointer to the array as a value into getValues. That is enough, because the method then modifies the array element, and by convention you're expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn't necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.





                                share














                                You can never pass by reference in Java, and one of the ways that is obvious is when you want to return more than one value from a method call. Consider the following bit of code in C++:



                                void getValues(int& arg1, int& arg2) {
                                arg1 = 1;
                                arg2 = 2;
                                }
                                void caller() {
                                int x;
                                int y;
                                getValues(x, y);
                                cout << "Result: " << x << " " << y << endl;
                                }


                                Sometimes you want to use the same pattern in Java, but you can't; at least not directly. Instead you could do something like this:



                                void getValues(int arg1, int arg2) {
                                arg1[0] = 1;
                                arg2[0] = 2;
                                }
                                void caller() {
                                int x = new int[1];
                                int y = new int[1];
                                getValues(x, y);
                                System.out.println("Result: " + x[0] + " " + y[0]);
                                }


                                As was explained in previous answers, in Java you're passing a pointer to the array as a value into getValues. That is enough, because the method then modifies the array element, and by convention you're expecting element 0 to contain the return value. Obviously you can do this in other ways, such as structuring your code so this isn't necessary, or constructing a class that can contain the return value or allow it to be set. But the simple pattern available to you in C++ above is not available in Java.






                                share













                                share


                                share








                                answered Mar 8 '09 at 6:28


























                                community wiki





                                Jared Oberhaus























                                    up vote
                                    44
                                    down vote













                                    Java is a call by value.



                                    How it works




                                    • You always pass a copy of the bits of the value of the reference!


                                    • If it's a primitive data type these bits contain the value of the primitive data type itself, That's why if we change the value of header inside the method then it does not reflect the changes outside.


                                    • If it's an object data type like Foo foo=new Foo() then in this case copy of the address of the object passes like file shortcut , suppose we have a text file abc.txt at C:desktop and suppose we make shortcut of the same file and put this inside C:desktopabc-shortcut so when you access the file from C:desktopabc.txt and write 'Stack Overflow' and close the file and again you open the file from shortcut then you write ' is the largest online community for programmers to learn' then total file change will be 'Stack Overflow is the largest online community for programmers to learn' which means it doesn't matter from where you open the file , each time we were accessing the same file , here we can assume Foo as a file and suppose foo stored at 123hd7h(original address like C:desktopabc.txt ) address and 234jdid(copied address like C:desktopabc-shortcut which actually contains the original address of the file inside) ..
                                      So for better understanding make shortcut file and feel...






                                    share



























                                      up vote
                                      44
                                      down vote













                                      Java is a call by value.



                                      How it works




                                      • You always pass a copy of the bits of the value of the reference!


                                      • If it's a primitive data type these bits contain the value of the primitive data type itself, That's why if we change the value of header inside the method then it does not reflect the changes outside.


                                      • If it's an object data type like Foo foo=new Foo() then in this case copy of the address of the object passes like file shortcut , suppose we have a text file abc.txt at C:desktop and suppose we make shortcut of the same file and put this inside C:desktopabc-shortcut so when you access the file from C:desktopabc.txt and write 'Stack Overflow' and close the file and again you open the file from shortcut then you write ' is the largest online community for programmers to learn' then total file change will be 'Stack Overflow is the largest online community for programmers to learn' which means it doesn't matter from where you open the file , each time we were accessing the same file , here we can assume Foo as a file and suppose foo stored at 123hd7h(original address like C:desktopabc.txt ) address and 234jdid(copied address like C:desktopabc-shortcut which actually contains the original address of the file inside) ..
                                        So for better understanding make shortcut file and feel...






                                      share

























                                        up vote
                                        44
                                        down vote










                                        up vote
                                        44
                                        down vote









                                        Java is a call by value.



                                        How it works




                                        • You always pass a copy of the bits of the value of the reference!


                                        • If it's a primitive data type these bits contain the value of the primitive data type itself, That's why if we change the value of header inside the method then it does not reflect the changes outside.


                                        • If it's an object data type like Foo foo=new Foo() then in this case copy of the address of the object passes like file shortcut , suppose we have a text file abc.txt at C:desktop and suppose we make shortcut of the same file and put this inside C:desktopabc-shortcut so when you access the file from C:desktopabc.txt and write 'Stack Overflow' and close the file and again you open the file from shortcut then you write ' is the largest online community for programmers to learn' then total file change will be 'Stack Overflow is the largest online community for programmers to learn' which means it doesn't matter from where you open the file , each time we were accessing the same file , here we can assume Foo as a file and suppose foo stored at 123hd7h(original address like C:desktopabc.txt ) address and 234jdid(copied address like C:desktopabc-shortcut which actually contains the original address of the file inside) ..
                                          So for better understanding make shortcut file and feel...






                                        share














                                        Java is a call by value.



                                        How it works




                                        • You always pass a copy of the bits of the value of the reference!


                                        • If it's a primitive data type these bits contain the value of the primitive data type itself, That's why if we change the value of header inside the method then it does not reflect the changes outside.


                                        • If it's an object data type like Foo foo=new Foo() then in this case copy of the address of the object passes like file shortcut , suppose we have a text file abc.txt at C:desktop and suppose we make shortcut of the same file and put this inside C:desktopabc-shortcut so when you access the file from C:desktopabc.txt and write 'Stack Overflow' and close the file and again you open the file from shortcut then you write ' is the largest online community for programmers to learn' then total file change will be 'Stack Overflow is the largest online community for programmers to learn' which means it doesn't matter from where you open the file , each time we were accessing the same file , here we can assume Foo as a file and suppose foo stored at 123hd7h(original address like C:desktopabc.txt ) address and 234jdid(copied address like C:desktopabc-shortcut which actually contains the original address of the file inside) ..
                                          So for better understanding make shortcut file and feel...







                                        share













                                        share


                                        share








                                        edited Sep 24 at 14:41


























                                        community wiki





                                        17 revs
                                        Himanshu arora























                                            up vote
                                            43
                                            down vote













                                            I thought I'd contribute this answer to add more details from the Specifications.



                                            First, What's the difference between passing by reference vs. passing by value?




                                            Passing by reference means the called functions' parameter will be the
                                            same as the callers' passed argument (not the value, but the identity
                                            - the variable itself).



                                            Pass by value means the called functions' parameter will be a copy of
                                            the callers' passed argument.




                                            Or from wikipedia, on the subject of pass-by-reference




                                            In call-by-reference evaluation (also referred to as
                                            pass-by-reference), a function receives an implicit reference to a
                                            variable used as argument, rather than a copy of its value. This
                                            typically means that the function can modify (i.e. assign to) the
                                            variable used as argument—something that will be seen by its caller.




                                            And on the subject of pass-by-value




                                            In call-by-value, the argument expression is evaluated, and the
                                            resulting value is bound to the corresponding variable in the function [...].
                                            If the function or procedure is able to assign values to its
                                            parameters, only its local copy is assigned [...].




                                            Second, we need to know what Java uses in its method invocations. The Java Language Specification states




                                            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.




                                            So it assigns (or binds) the value of the argument to the corresponding parameter variable.



                                            What is the value of the argument?



                                            Let's consider reference types, the Java Virtual Machine Specification states




                                            There are three kinds of reference types: class types, array types,
                                            and interface types. Their values are references to dynamically
                                            created class instances, arrays, or class instances or arrays that
                                            implement interfaces, respectively.




                                            The Java Language Specification also states




                                            The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.




                                            The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (new ...) all resolve to a reference type value.



                                            So



                                            public void method (String param) {}
                                            ...
                                            String var = new String("ref");
                                            method(var);
                                            method(var.toString());
                                            method(new String("ref"));


                                            all bind the value of a reference to a String instance to the method's newly created parameter, param. This is exactly what the definition of pass-by-value describes. As such, Java is pass-by-value.



                                            The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation. The definition of pass-by-reference was




                                            This typically means that the function can modify (i.e. assign to) the
                                            variable used as argument—something that will be seen by its caller.




                                            In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. Modifying the object referenced by the variable is a different concept entirely.





                                            Primitive values are also defined in the Java Virtual Machine Specification, here. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).





                                            share























                                            • Thank you for beginning with a discussion of the definitions of the terms. That sets your answer apart from the crowd and is necessary for a proper understanding.
                                              – Aaron
                                              Aug 2 '17 at 15:39















                                            up vote
                                            43
                                            down vote













                                            I thought I'd contribute this answer to add more details from the Specifications.



                                            First, What's the difference between passing by reference vs. passing by value?




                                            Passing by reference means the called functions' parameter will be the
                                            same as the callers' passed argument (not the value, but the identity
                                            - the variable itself).



                                            Pass by value means the called functions' parameter will be a copy of
                                            the callers' passed argument.




                                            Or from wikipedia, on the subject of pass-by-reference




                                            In call-by-reference evaluation (also referred to as
                                            pass-by-reference), a function receives an implicit reference to a
                                            variable used as argument, rather than a copy of its value. This
                                            typically means that the function can modify (i.e. assign to) the
                                            variable used as argument—something that will be seen by its caller.




                                            And on the subject of pass-by-value




                                            In call-by-value, the argument expression is evaluated, and the
                                            resulting value is bound to the corresponding variable in the function [...].
                                            If the function or procedure is able to assign values to its
                                            parameters, only its local copy is assigned [...].




                                            Second, we need to know what Java uses in its method invocations. The Java Language Specification states




                                            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.




                                            So it assigns (or binds) the value of the argument to the corresponding parameter variable.



                                            What is the value of the argument?



                                            Let's consider reference types, the Java Virtual Machine Specification states




                                            There are three kinds of reference types: class types, array types,
                                            and interface types. Their values are references to dynamically
                                            created class instances, arrays, or class instances or arrays that
                                            implement interfaces, respectively.




                                            The Java Language Specification also states




                                            The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.




                                            The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (new ...) all resolve to a reference type value.



                                            So



                                            public void method (String param) {}
                                            ...
                                            String var = new String("ref");
                                            method(var);
                                            method(var.toString());
                                            method(new String("ref"));


                                            all bind the value of a reference to a String instance to the method's newly created parameter, param. This is exactly what the definition of pass-by-value describes. As such, Java is pass-by-value.



                                            The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation. The definition of pass-by-reference was




                                            This typically means that the function can modify (i.e. assign to) the
                                            variable used as argument—something that will be seen by its caller.




                                            In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. Modifying the object referenced by the variable is a different concept entirely.





                                            Primitive values are also defined in the Java Virtual Machine Specification, here. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).





                                            share























                                            • Thank you for beginning with a discussion of the definitions of the terms. That sets your answer apart from the crowd and is necessary for a proper understanding.
                                              – Aaron
                                              Aug 2 '17 at 15:39













                                            up vote
                                            43
                                            down vote










                                            up vote
                                            43
                                            down vote









                                            I thought I'd contribute this answer to add more details from the Specifications.



                                            First, What's the difference between passing by reference vs. passing by value?




                                            Passing by reference means the called functions' parameter will be the
                                            same as the callers' passed argument (not the value, but the identity
                                            - the variable itself).



                                            Pass by value means the called functions' parameter will be a copy of
                                            the callers' passed argument.




                                            Or from wikipedia, on the subject of pass-by-reference




                                            In call-by-reference evaluation (also referred to as
                                            pass-by-reference), a function receives an implicit reference to a
                                            variable used as argument, rather than a copy of its value. This
                                            typically means that the function can modify (i.e. assign to) the
                                            variable used as argument—something that will be seen by its caller.




                                            And on the subject of pass-by-value




                                            In call-by-value, the argument expression is evaluated, and the
                                            resulting value is bound to the corresponding variable in the function [...].
                                            If the function or procedure is able to assign values to its
                                            parameters, only its local copy is assigned [...].




                                            Second, we need to know what Java uses in its method invocations. The Java Language Specification states




                                            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.




                                            So it assigns (or binds) the value of the argument to the corresponding parameter variable.



                                            What is the value of the argument?



                                            Let's consider reference types, the Java Virtual Machine Specification states




                                            There are three kinds of reference types: class types, array types,
                                            and interface types. Their values are references to dynamically
                                            created class instances, arrays, or class instances or arrays that
                                            implement interfaces, respectively.




                                            The Java Language Specification also states




                                            The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.




                                            The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (new ...) all resolve to a reference type value.



                                            So



                                            public void method (String param) {}
                                            ...
                                            String var = new String("ref");
                                            method(var);
                                            method(var.toString());
                                            method(new String("ref"));


                                            all bind the value of a reference to a String instance to the method's newly created parameter, param. This is exactly what the definition of pass-by-value describes. As such, Java is pass-by-value.



                                            The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation. The definition of pass-by-reference was




                                            This typically means that the function can modify (i.e. assign to) the
                                            variable used as argument—something that will be seen by its caller.




                                            In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. Modifying the object referenced by the variable is a different concept entirely.





                                            Primitive values are also defined in the Java Virtual Machine Specification, here. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).





                                            share














                                            I thought I'd contribute this answer to add more details from the Specifications.



                                            First, What's the difference between passing by reference vs. passing by value?




                                            Passing by reference means the called functions' parameter will be the
                                            same as the callers' passed argument (not the value, but the identity
                                            - the variable itself).



                                            Pass by value means the called functions' parameter will be a copy of
                                            the callers' passed argument.




                                            Or from wikipedia, on the subject of pass-by-reference




                                            In call-by-reference evaluation (also referred to as
                                            pass-by-reference), a function receives an implicit reference to a
                                            variable used as argument, rather than a copy of its value. This
                                            typically means that the function can modify (i.e. assign to) the
                                            variable used as argument—something that will be seen by its caller.




                                            And on the subject of pass-by-value




                                            In call-by-value, the argument expression is evaluated, and the
                                            resulting value is bound to the corresponding variable in the function [...].
                                            If the function or procedure is able to assign values to its
                                            parameters, only its local copy is assigned [...].




                                            Second, we need to know what Java uses in its method invocations. The Java Language Specification states




                                            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.




                                            So it assigns (or binds) the value of the argument to the corresponding parameter variable.



                                            What is the value of the argument?



                                            Let's consider reference types, the Java Virtual Machine Specification states




                                            There are three kinds of reference types: class types, array types,
                                            and interface types. Their values are references to dynamically
                                            created class instances, arrays, or class instances or arrays that
                                            implement interfaces, respectively.




                                            The Java Language Specification also states




                                            The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object.




                                            The value of an argument (of some reference type) is a pointer to an object. Note that a variable, an invocation of a method with a reference type return type, and an instance creation expression (new ...) all resolve to a reference type value.



                                            So



                                            public void method (String param) {}
                                            ...
                                            String var = new String("ref");
                                            method(var);
                                            method(var.toString());
                                            method(new String("ref"));


                                            all bind the value of a reference to a String instance to the method's newly created parameter, param. This is exactly what the definition of pass-by-value describes. As such, Java is pass-by-value.



                                            The fact that you can follow the reference to invoke a method or access a field of the referenced object is completely irrelevant to the conversation. The definition of pass-by-reference was




                                            This typically means that the function can modify (i.e. assign to) the
                                            variable used as argument—something that will be seen by its caller.




                                            In Java, modifying the variable means reassigning it. In Java, if you reassigned the variable within the method, it would go unnoticed to the caller. Modifying the object referenced by the variable is a different concept entirely.





                                            Primitive values are also defined in the Java Virtual Machine Specification, here. The value of the type is the corresponding integral or floating point value, encoded appropriately (8, 16, 32, 64, etc. bits).






                                            share













                                            share


                                            share








                                            edited May 23 '17 at 12:18


























                                            community wiki





                                            3 revs
                                            Sotirios Delimanolis













                                            • Thank you for beginning with a discussion of the definitions of the terms. That sets your answer apart from the crowd and is necessary for a proper understanding.
                                              – Aaron
                                              Aug 2 '17 at 15:39


















                                            • Thank you for beginning with a discussion of the definitions of the terms. That sets your answer apart from the crowd and is necessary for a proper understanding.
                                              – Aaron
                                              Aug 2 '17 at 15:39
















                                            Thank you for beginning with a discussion of the definitions of the terms. That sets your answer apart from the crowd and is necessary for a proper understanding.
                                            – Aaron
                                            Aug 2 '17 at 15:39




                                            Thank you for beginning with a discussion of the definitions of the terms. That sets your answer apart from the crowd and is necessary for a proper understanding.
                                            – Aaron
                                            Aug 2 '17 at 15:39










                                            up vote
                                            34
                                            down vote













                                            The distinction, or perhaps just the way I remember as I used to be under the same impression as the original poster is this: Java is always pass by value. All objects( in Java, anything except for primitives) in Java are references. These references are passed by value.





                                            share



















                                            • 2




                                              I find your second-to-last sentence very misleading. It's not true that "all objects in Java are references". It's only the references to those objects that are references.
                                              – Dawood ibn Kareem
                                              Jan 25 '17 at 10:09















                                            up vote
                                            34
                                            down vote













                                            The distinction, or perhaps just the way I remember as I used to be under the same impression as the original poster is this: Java is always pass by value. All objects( in Java, anything except for primitives) in Java are references. These references are passed by value.





                                            share



















                                            • 2




                                              I find your second-to-last sentence very misleading. It's not true that "all objects in Java are references". It's only the references to those objects that are references.
                                              – Dawood ibn Kareem
                                              Jan 25 '17 at 10:09













                                            up vote
                                            34
                                            down vote










                                            up vote
                                            34
                                            down vote









                                            The distinction, or perhaps just the way I remember as I used to be under the same impression as the original poster is this: Java is always pass by value. All objects( in Java, anything except for primitives) in Java are references. These references are passed by value.





                                            share














                                            The distinction, or perhaps just the way I remember as I used to be under the same impression as the original poster is this: Java is always pass by value. All objects( in Java, anything except for primitives) in Java are references. These references are passed by value.






                                            share













                                            share


                                            share








                                            edited Apr 30 '14 at 4:50


























                                            community wiki





                                            2 revs, 2 users 50%
                                            shsteimer









                                            • 2




                                              I find your second-to-last sentence very misleading. It's not true that "all objects in Java are references". It's only the references to those objects that are references.
                                              – Dawood ibn Kareem
                                              Jan 25 '17 at 10:09














                                            • 2




                                              I find your second-to-last sentence very misleading. It's not true that "all objects in Java are references". It's only the references to those objects that are references.
                                              – Dawood ibn Kareem
                                              Jan 25 '17 at 10:09








                                            2




                                            2




                                            I find your second-to-last sentence very misleading. It's not true that "all objects in Java are references". It's only the references to those objects that are references.
                                            – Dawood ibn Kareem
                                            Jan 25 '17 at 10:09




                                            I find your second-to-last sentence very misleading. It's not true that "all objects in Java are references". It's only the references to those objects that are references.
                                            – Dawood ibn Kareem
                                            Jan 25 '17 at 10:09










                                            up vote
                                            31
                                            down vote













                                            As many people mentioned it before, Java is always pass-by-value



                                            Here is another example that will help you understand the difference (the classic swap example):



                                            public class Test {
                                            public static void main(String args) {
                                            Integer a = new Integer(2);
                                            Integer b = new Integer(3);
                                            System.out.println("Before: a = " + a + ", b = " + b);
                                            swap(a,b);
                                            System.out.println("After: a = " + a + ", b = " + b);
                                            }

                                            public static swap(Integer iA, Integer iB) {
                                            Integer tmp = iA;
                                            iA = iB;
                                            iB = tmp;
                                            }
                                            }


                                            Prints:




                                            Before: a = 2, b = 3

                                            After: a = 2, b = 3




                                            This happens because iA and iB are new local reference variables that have the same value of the passed references (they point to a and b respectively). So, trying to change the references of iA or iB will only change in the local scope and not outside of this method.





                                            share























                                            • i understood with this answer
                                              – Kumaresan Perumal
                                              Apr 25 at 18:04















                                            up vote
                                            31
                                            down vote













                                            As many people mentioned it before, Java is always pass-by-value



                                            Here is another example that will help you understand the difference (the classic swap example):



                                            public class Test {
                                            public static void main(String args) {
                                            Integer a = new Integer(2);
                                            Integer b = new Integer(3);
                                            System.out.println("Before: a = " + a + ", b = " + b);
                                            swap(a,b);
                                            System.out.println("After: a = " + a + ", b = " + b);
                                            }

                                            public static swap(Integer iA, Integer iB) {
                                            Integer tmp = iA;
                                            iA = iB;
                                            iB = tmp;
                                            }
                                            }


                                            Prints:




                                            Before: a = 2, b = 3

                                            After: a = 2, b = 3




                                            This happens because iA and iB are new local reference variables that have the same value of the passed references (they point to a and b respectively). So, trying to change the references of iA or iB will only change in the local scope and not outside of this method.





                                            share























                                            • i understood with this answer
                                              – Kumaresan Perumal
                                              Apr 25 at 18:04













                                            up vote
                                            31
                                            down vote










                                            up vote
                                            31
                                            down vote









                                            As many people mentioned it before, Java is always pass-by-value



                                            Here is another example that will help you understand the difference (the classic swap example):



                                            public class Test {
                                            public static void main(String args) {
                                            Integer a = new Integer(2);
                                            Integer b = new Integer(3);
                                            System.out.println("Before: a = " + a + ", b = " + b);
                                            swap(a,b);
                                            System.out.println("After: a = " + a + ", b = " + b);
                                            }

                                            public static swap(Integer iA, Integer iB) {
                                            Integer tmp = iA;
                                            iA = iB;
                                            iB = tmp;
                                            }
                                            }


                                            Prints:




                                            Before: a = 2, b = 3

                                            After: a = 2, b = 3




                                            This happens because iA and iB are new local reference variables that have the same value of the passed references (they point to a and b respectively). So, trying to change the references of iA or iB will only change in the local scope and not outside of this method.





                                            share














                                            As many people mentioned it before, Java is always pass-by-value



                                            Here is another example that will help you understand the difference (the classic swap example):



                                            public class Test {
                                            public static void main(String args) {
                                            Integer a = new Integer(2);
                                            Integer b = new Integer(3);
                                            System.out.println("Before: a = " + a + ", b = " + b);
                                            swap(a,b);
                                            System.out.println("After: a = " + a + ", b = " + b);
                                            }

                                            public static swap(Integer iA, Integer iB) {
                                            Integer tmp = iA;
                                            iA = iB;
                                            iB = tmp;
                                            }
                                            }


                                            Prints:




                                            Before: a = 2, b = 3

                                            After: a = 2, b = 3




                                            This happens because iA and iB are new local reference variables that have the same value of the passed references (they point to a and b respectively). So, trying to change the references of iA or iB will only change in the local scope and not outside of this method.






                                            share













                                            share


                                            share








                                            answered Sep 3 '08 at 20:01


























                                            community wiki





                                            pek













                                            • i understood with this answer
                                              – Kumaresan Perumal
                                              Apr 25 at 18:04


















                                            • i understood with this answer
                                              – Kumaresan Perumal
                                              Apr 25 at 18:04
















                                            i understood with this answer
                                            – Kumaresan Perumal
                                            Apr 25 at 18:04




                                            i understood with this answer
                                            – Kumaresan Perumal
                                            Apr 25 at 18:04










                                            up vote
                                            30
                                            down vote













                                            Java has only pass by value. A very simple example to validate this.



                                            public void test() {
                                            MyClass obj = null;
                                            init(obj);
                                            //After calling init method, obj still points to null
                                            //this is because obj is passed as value and not as reference.
                                            }
                                            private void init(MyClass objVar) {
                                            objVar = new MyClass();
                                            }




                                            share



















                                            • 4




                                              This is the clearest, simplest way to see that Java passes by value. The value of obj (null) was passed to init, not a reference to obj.
                                              – David Schwartz
                                              Jun 10 '17 at 23:24















                                            up vote
                                            30
                                            down vote













                                            Java has only pass by value. A very simple example to validate this.



                                            public void test() {
                                            MyClass obj = null;
                                            init(obj);
                                            //After calling init method, obj still points to null
                                            //this is because obj is passed as value and not as reference.
                                            }
                                            private void init(MyClass objVar) {
                                            objVar = new MyClass();
                                            }




                                            share



















                                            • 4




                                              This is the clearest, simplest way to see that Java passes by value. The value of obj (null) was passed to init, not a reference to obj.
                                              – David Schwartz
                                              Jun 10 '17 at 23:24













                                            up vote
                                            30
                                            down vote










                                            up vote
                                            30
                                            down vote









                                            Java has only pass by value. A very simple example to validate this.



                                            public void test() {
                                            MyClass obj = null;
                                            init(obj);
                                            //After calling init method, obj still points to null
                                            //this is because obj is passed as value and not as reference.
                                            }
                                            private void init(MyClass objVar) {
                                            objVar = new MyClass();
                                            }




                                            share














                                            Java has only pass by value. A very simple example to validate this.



                                            public void test() {
                                            MyClass obj = null;
                                            init(obj);
                                            //After calling init method, obj still points to null
                                            //this is because obj is passed as value and not as reference.
                                            }
                                            private void init(MyClass objVar) {
                                            objVar = new MyClass();
                                            }





                                            share













                                            share


                                            share








                                            edited Apr 29 '17 at 4:31


























                                            community wiki





                                            2 revs, 2 users 86%
                                            Gaurav









                                            • 4




                                              This is the clearest, simplest way to see that Java passes by value. The value of obj (null) was passed to init, not a reference to obj.
                                              – David Schwartz
                                              Jun 10 '17 at 23:24














                                            • 4




                                              This is the clearest, simplest way to see that Java passes by value. The value of obj (null) was passed to init, not a reference to obj.
                                              – David Schwartz
                                              Jun 10 '17 at 23:24








                                            4




                                            4




                                            This is the clearest, simplest way to see that Java passes by value. The value of obj (null) was passed to init, not a reference to obj.
                                            – David Schwartz
                                            Jun 10 '17 at 23:24




                                            This is the clearest, simplest way to see that Java passes by value. The value of obj (null) was passed to init, not a reference to obj.
                                            – David Schwartz
                                            Jun 10 '17 at 23:24










                                            up vote
                                            30
                                            down vote













                                            In Java only references are passed and are passed by value:



                                            Java arguments are all passed by value (the reference is copied when used by the method) :



                                            In the case of primitive types, Java behaviour is simple:
                                            The value is copied in another instance of the primitive type.



                                            In case of Objects, this is the same:
                                            Object variables are pointers (buckets) holding only Object’s address that was created using the "new" keyword, and are copied like primitive types.



                                            The behaviour can appear different from primitive types: Because the copied object-variable contains the same address (to the same Object)
                                            Object's content/members might still be modified within a method and later access outside, giving the illusion that the (containing) Object itself was passed by reference.



                                            "String" Objects appear to be a perfect counter-example to the urban legend saying that "Objects are passed by reference":



                                            In effect, within a method you will never be able, to update the value of a String passed as argument:



                                            A String Object, holds characters by an array declared final that can't be modified.
                                            Only the address of the Object might be replaced by another using "new".
                                            Using "new" to update the variable, will not let the Object be accessed from outside, since the variable was initially passed by value and copied.





                                            share























                                            • So it's byRef in regards to objects and byVal in regards to primitives?
                                              – Mox
                                              Jan 18 '17 at 11:40










                                            • @mox please read: Objects are not passed by reference, this is a ledgend: String a=new String("unchanged");
                                              – user1767316
                                              Jan 25 '17 at 23:28












                                            • public void changeit(String changeit){changit = "changed";} changeIt(a); assert(a.equals("unchanged"));
                                              – user1767316
                                              Jan 25 '17 at 23:35










                                            • This is yet another great example of the fallacy of the "it is not pass by reference" semantics argument. This answer says right in the bold, first sentence: "only references are passed." Either a reference is passed, or a reference is not passed. You just said yourself that a reference is passed. By saying "it is not passed by reference since a reference is passed but..." you are trying to make a point by mangling English.
                                              – Aaron
                                              Aug 2 '17 at 15:07










                                            • @Aaron "Pass by reference" does not mean "pass a value that is a member of a type that is called a 'reference' in Java". The two uses of "reference" mean different things.
                                              – philipxy
                                              Sep 27 '17 at 8:36

















                                            up vote
                                            30
                                            down vote













                                            In Java only references are passed and are passed by value:



                                            Java arguments are all passed by value (the reference is copied when used by the method) :



                                            In the case of primitive types, Java behaviour is simple:
                                            The value is copied in another instance of the primitive type.



                                            In case of Objects, this is the same:
                                            Object variables are pointers (buckets) holding only Object’s address that was created using the "new" keyword, and are copied like primitive types.



                                            The behaviour can appear different from primitive types: Because the copied object-variable contains the same address (to the same Object)
                                            Object's content/members might still be modified within a method and later access outside, giving the illusion that the (containing) Object itself was passed by reference.



                                            "String" Objects appear to be a perfect counter-example to the urban legend saying that "Objects are passed by reference":



                                            In effect, within a method you will never be able, to update the value of a String passed as argument:



                                            A String Object, holds characters by an array declared final that can't be modified.
                                            Only the address of the Object might be replaced by another using "new".
                                            Using "new" to update the variable, will not let the Object be accessed from outside, since the variable was initially passed by value and copied.





                                            share























                                            • So it's byRef in regards to objects and byVal in regards to primitives?
                                              – Mox
                                              Jan 18 '17 at 11:40










                                            • @mox please read: Objects are not passed by reference, this is a ledgend: String a=new String("unchanged");
                                              – user1767316
                                              Jan 25 '17 at 23:28












                                            • public void changeit(String changeit){changit = "changed";} changeIt(a); assert(a.equals("unchanged"));
                                              – user1767316
                                              Jan 25 '17 at 23:35










                                            • This is yet another great example of the fallacy of the "it is not pass by reference" semantics argument. This answer says right in the bold, first sentence: "only references are passed." Either a reference is passed, or a reference is not passed. You just said yourself that a reference is passed. By saying "it is not passed by reference since a reference is passed but..." you are trying to make a point by mangling English.
                                              – Aaron
                                              Aug 2 '17 at 15:07










                                            • @Aaron "Pass by reference" does not mean "pass a value that is a member of a type that is called a 'reference' in Java". The two uses of "reference" mean different things.
                                              – philipxy
                                              Sep 27 '17 at 8:36















                                            up vote
                                            30
                                            down vote










                                            up vote
                                            30
                                            down vote









                                            In Java only references are passed and are passed by value:



                                            Java arguments are all passed by value (the reference is copied when used by the method) :



                                            In the case of primitive types, Java behaviour is simple:
                                            The value is copied in another instance of the primitive type.



                                            In case of Objects, this is the same:
                                            Object variables are pointers (buckets) holding only Object’s address that was created using the "new" keyword, and are copied like primitive types.



                                            The behaviour can appear different from primitive types: Because the copied object-variable contains the same address (to the same Object)
                                            Object's content/members might still be modified within a method and later access outside, giving the illusion that the (containing) Object itself was passed by reference.



                                            "String" Objects appear to be a perfect counter-example to the urban legend saying that "Objects are passed by reference":



                                            In effect, within a method you will never be able, to update the value of a String passed as argument:



                                            A String Object, holds characters by an array declared final that can't be modified.
                                            Only the address of the Object might be replaced by another using "new".
                                            Using "new" to update the variable, will not let the Object be accessed from outside, since the variable was initially passed by value and copied.





                                            share














                                            In Java only references are passed and are passed by value:



                                            Java arguments are all passed by value (the reference is copied when used by the method) :



                                            In the case of primitive types, Java behaviour is simple:
                                            The value is copied in another instance of the primitive type.



                                            In case of Objects, this is the same:
                                            Object variables are pointers (buckets) holding only Object’s address that was created using the "new" keyword, and are copied like primitive types.



                                            The behaviour can appear different from primitive types: Because the copied object-variable contains the same address (to the same Object)
                                            Object's content/members might still be modified within a method and later access outside, giving the illusion that the (containing) Object itself was passed by reference.



                                            "String" Objects appear to be a perfect counter-example to the urban legend saying that "Objects are passed by reference":



                                            In effect, within a method you will never be able, to update the value of a String passed as argument:



                                            A String Object, holds characters by an array declared final that can't be modified.
                                            Only the address of the Object might be replaced by another using "new".
                                            Using "new" to update the variable, will not let the Object be accessed from outside, since the variable was initially passed by value and copied.






                                            share













                                            share


                                            share








                                            edited Nov 5 '17 at 20:39


























                                            community wiki





                                            5 revs
                                            user1767316













                                            • So it's byRef in regards to objects and byVal in regards to primitives?
                                              – Mox
                                              Jan 18 '17 at 11:40










                                            • @mox please read: Objects are not passed by reference, this is a ledgend: String a=new String("unchanged");
                                              – user1767316
                                              Jan 25 '17 at 23:28












                                            • public void changeit(String changeit){changit = "changed";} changeIt(a); assert(a.equals("unchanged"));
                                              – user1767316
                                              Jan 25 '17 at 23:35










                                            • This is yet another great example of the fallacy of the "it is not pass by reference" semantics argument. This answer says right in the bold, first sentence: "only references are passed." Either a reference is passed, or a reference is not passed. You just said yourself that a reference is passed. By saying "it is not passed by reference since a reference is passed but..." you are trying to make a point by mangling English.
                                              – Aaron
                                              Aug 2 '17 at 15:07










                                            • @Aaron "Pass by reference" does not mean "pass a value that is a member of a type that is called a 'reference' in Java". The two uses of "reference" mean different things.
                                              – philipxy
                                              Sep 27 '17 at 8:36




















                                            • So it's byRef in regards to objects and byVal in regards to primitives?
                                              – Mox
                                              Jan 18 '17 at 11:40










                                            • @mox please read: Objects are not passed by reference, this is a ledgend: String a=new String("unchanged");
                                              – user1767316
                                              Jan 25 '17 at 23:28












                                            • public void changeit(String changeit){changit = "changed";} changeIt(a); assert(a.equals("unchanged"));
                                              – user1767316
                                              Jan 25 '17 at 23:35










                                            • This is yet another great example of the fallacy of the "it is not pass by reference" semantics argument. This answer says right in the bold, first sentence: "only references are passed." Either a reference is passed, or a reference is not passed. You just said yourself that a reference is passed. By saying "it is not passed by reference since a reference is passed but..." you are trying to make a point by mangling English.
                                              – Aaron
                                              Aug 2 '17 at 15:07










                                            • @Aaron "Pass by reference" does not mean "pass a value that is a member of a type that is called a 'reference' in Java". The two uses of "reference" mean different things.
                                              – philipxy
                                              Sep 27 '17 at 8:36


















                                            So it's byRef in regards to objects and byVal in regards to primitives?
                                            – Mox
                                            Jan 18 '17 at 11:40




                                            So it's byRef in regards to objects and byVal in regards to primitives?
                                            – Mox
                                            Jan 18 '17 at 11:40












                                            @mox please read: Objects are not passed by reference, this is a ledgend: String a=new String("unchanged");
                                            – user1767316
                                            Jan 25 '17 at 23:28






                                            @mox please read: Objects are not passed by reference, this is a ledgend: String a=new String("unchanged");
                                            – user1767316
                                            Jan 25 '17 at 23:28














                                            public void changeit(String changeit){changit = "changed";} changeIt(a); assert(a.equals("unchanged"));
                                            – user1767316
                                            Jan 25 '17 at 23:35




                                            public void changeit(String changeit){changit = "changed";} changeIt(a); assert(a.equals("unchanged"));
                                            – user1767316
                                            Jan 25 '17 at 23:35












                                            This is yet another great example of the fallacy of the "it is not pass by reference" semantics argument. This answer says right in the bold, first sentence: "only references are passed." Either a reference is passed, or a reference is not passed. You just said yourself that a reference is passed. By saying "it is not passed by reference since a reference is passed but..." you are trying to make a point by mangling English.
                                            – Aaron
                                            Aug 2 '17 at 15:07




                                            This is yet another great example of the fallacy of the "it is not pass by reference" semantics argument. This answer says right in the bold, first sentence: "only references are passed." Either a reference is passed, or a reference is not passed. You just said yourself that a reference is passed. By saying "it is not passed by reference since a reference is passed but..." you are trying to make a point by mangling English.
                                            – Aaron
                                            Aug 2 '17 at 15:07












                                            @Aaron "Pass by reference" does not mean "pass a value that is a member of a type that is called a 'reference' in Java". The two uses of "reference" mean different things.
                                            – philipxy
                                            Sep 27 '17 at 8:36






                                            @Aaron "Pass by reference" does not mean "pass a value that is a member of a type that is called a 'reference' in Java". The two uses of "reference" mean different things.
                                            – philipxy
                                            Sep 27 '17 at 8:36












                                            up vote
                                            29
                                            down vote













                                            I always think of it as "pass by copy". It is a copy of the value be it primitive or reference. If it is a primitive it is a copy of the bits that are the value and if it is an Object it is a copy of the reference.



                                            public class PassByCopy{
                                            public static void changeName(Dog d){
                                            d.name = "Fido";
                                            }
                                            public static void main(String args){
                                            Dog d = new Dog("Maxx");
                                            System.out.println("name= "+ d.name);
                                            changeName(d);
                                            System.out.println("name= "+ d.name);
                                            }
                                            }
                                            class Dog{
                                            public String name;
                                            public Dog(String s){
                                            this.name = s;
                                            }
                                            }


                                            output of java PassByCopy:




                                            name= Maxx

                                            name= Fido




                                            Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.





                                            share



















                                            • 3




                                              "pass by copy" is what pass-by-value means.
                                              – T.J. Crowder
                                              Aug 7 '16 at 8:46















                                            up vote
                                            29
                                            down vote













                                            I always think of it as "pass by copy". It is a copy of the value be it primitive or reference. If it is a primitive it is a copy of the bits that are the value and if it is an Object it is a copy of the reference.



                                            public class PassByCopy{
                                            public static void changeName(Dog d){
                                            d.name = "Fido";
                                            }
                                            public static void main(String args){
                                            Dog d = new Dog("Maxx");
                                            System.out.println("name= "+ d.name);
                                            changeName(d);
                                            System.out.println("name= "+ d.name);
                                            }
                                            }
                                            class Dog{
                                            public String name;
                                            public Dog(String s){
                                            this.name = s;
                                            }
                                            }


                                            output of java PassByCopy:




                                            name= Maxx

                                            name= Fido




                                            Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.





                                            share



















                                            • 3




                                              "pass by copy" is what pass-by-value means.
                                              – T.J. Crowder
                                              Aug 7 '16 at 8:46













                                            up vote
                                            29
                                            down vote










                                            up vote
                                            29
                                            down vote









                                            I always think of it as "pass by copy". It is a copy of the value be it primitive or reference. If it is a primitive it is a copy of the bits that are the value and if it is an Object it is a copy of the reference.



                                            public class PassByCopy{
                                            public static void changeName(Dog d){
                                            d.name = "Fido";
                                            }
                                            public static void main(String args){
                                            Dog d = new Dog("Maxx");
                                            System.out.println("name= "+ d.name);
                                            changeName(d);
                                            System.out.println("name= "+ d.name);
                                            }
                                            }
                                            class Dog{
                                            public String name;
                                            public Dog(String s){
                                            this.name = s;
                                            }
                                            }


                                            output of java PassByCopy:




                                            name= Maxx

                                            name= Fido




                                            Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.





                                            share














                                            I always think of it as "pass by copy". It is a copy of the value be it primitive or reference. If it is a primitive it is a copy of the bits that are the value and if it is an Object it is a copy of the reference.



                                            public class PassByCopy{
                                            public static void changeName(Dog d){
                                            d.name = "Fido";
                                            }
                                            public static void main(String args){
                                            Dog d = new Dog("Maxx");
                                            System.out.println("name= "+ d.name);
                                            changeName(d);
                                            System.out.println("name= "+ d.name);
                                            }
                                            }
                                            class Dog{
                                            public String name;
                                            public Dog(String s){
                                            this.name = s;
                                            }
                                            }


                                            output of java PassByCopy:




                                            name= Maxx

                                            name= Fido




                                            Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.






                                            share













                                            share


                                            share








                                            edited Jan 12 '09 at 20:47


























                                            community wiki





                                            3 revs, 2 users 71%
                                            SWD










                                            • 3




                                              "pass by copy" is what pass-by-value means.
                                              – T.J. Crowder
                                              Aug 7 '16 at 8:46














                                            • 3




                                              "pass by copy" is what pass-by-value means.
                                              – T.J. Crowder
                                              Aug 7 '16 at 8:46








                                            3




                                            3




                                            "pass by copy" is what pass-by-value means.
                                            – T.J. Crowder
                                            Aug 7 '16 at 8:46




                                            "pass by copy" is what pass-by-value means.
                                            – T.J. Crowder
                                            Aug 7 '16 at 8:46










                                            up vote
                                            24
                                            down vote













                                            I have created a thread devoted to these kind of questions for any programming languages here.



                                            Java is also mentioned. Here is the short summary:




                                            • Java passes it parameters by value

                                            • "by value" is the only way in java to pass a parameter to a method

                                            • using methods from the object given as parameter will alter the
                                              object as the references point to
                                              the original objects. (if that
                                              method itself alters some values)





                                            share



























                                              up vote
                                              24
                                              down vote













                                              I have created a thread devoted to these kind of questions for any programming languages here.



                                              Java is also mentioned. Here is the short summary:




                                              • Java passes it parameters by value

                                              • "by value" is the only way in java to pass a parameter to a method

                                              • using methods from the object given as parameter will alter the
                                                object as the references point to
                                                the original objects. (if that
                                                method itself alters some values)





                                              share

























                                                up vote
                                                24
                                                down vote










                                                up vote
                                                24
                                                down vote









                                                I have created a thread devoted to these kind of questions for any programming languages here.



                                                Java is also mentioned. Here is the short summary:




                                                • Java passes it parameters by value

                                                • "by value" is the only way in java to pass a parameter to a method

                                                • using methods from the object given as parameter will alter the
                                                  object as the references point to
                                                  the original objects. (if that
                                                  method itself alters some values)





                                                share














                                                I have created a thread devoted to these kind of questions for any programming languages here.



                                                Java is also mentioned. Here is the short summary:




                                                • Java passes it parameters by value

                                                • "by value" is the only way in java to pass a parameter to a method

                                                • using methods from the object given as parameter will alter the
                                                  object as the references point to
                                                  the original objects. (if that
                                                  method itself alters some values)






                                                share













                                                share


                                                share








                                                edited May 23 '17 at 12:02


























                                                community wiki





                                                2 revs
                                                sven























                                                    up vote
                                                    23
                                                    down vote













                                                    A few corrections to some posts.



                                                    C does NOT support pass by reference. It is ALWAYS pass by value. C++ does support pass by reference, but is not the default and is quite dangerous.



                                                    It doesn't matter what the value is in Java: primitive or address(roughly) of object, it is ALWAYS passed by value.



                                                    If a Java object "behaves" like it is being passed by reference, that is a property of mutability and has absolutely nothing to do with passing mechanisms.



                                                    I am not sure why this is so confusing, perhaps because so many Java "programmers" are not formally trained, and thus do not understand what is really going on in memory?





                                                    share



















                                                    • 1




                                                      +1. What C does support, is treating references (which C calls pointers) as first-class values, and then passing them by value.
                                                      – Jörg W Mittag
                                                      Sep 7 '10 at 22:02






                                                    • 1




                                                      Yeah, in C you can create pointers not only on objects, but on arbitrary variables - so you can easily simulate "call-by-reference" of any variable. In Java this works only for variables which have a surrounding object, which you can give.
                                                      – Paŭlo Ebermann
                                                      Feb 3 '11 at 1:27















                                                    up vote
                                                    23
                                                    down vote













                                                    A few corrections to some posts.



                                                    C does NOT support pass by reference. It is ALWAYS pass by value. C++ does support pass by reference, but is not the default and is quite dangerous.



                                                    It doesn't matter what the value is in Java: primitive or address(roughly) of object, it is ALWAYS passed by value.



                                                    If a Java object "behaves" like it is being passed by reference, that is a property of mutability and has absolutely nothing to do with passing mechanisms.



                                                    I am not sure why this is so confusing, perhaps because so many Java "programmers" are not formally trained, and thus do not understand what is really going on in memory?





                                                    share



















                                                    • 1




                                                      +1. What C does support, is treating references (which C calls pointers) as first-class values, and then passing them by value.
                                                      – Jörg W Mittag
                                                      Sep 7 '10 at 22:02






                                                    • 1




                                                      Yeah, in C you can create pointers not only on objects, but on arbitrary variables - so you can easily simulate "call-by-reference" of any variable. In Java this works only for variables which have a surrounding object, which you can give.
                                                      – Paŭlo Ebermann
                                                      Feb 3 '11 at 1:27













                                                    up vote
                                                    23
                                                    down vote










                                                    up vote
                                                    23
                                                    down vote









                                                    A few corrections to some posts.



                                                    C does NOT support pass by reference. It is ALWAYS pass by value. C++ does support pass by reference, but is not the default and is quite dangerous.



                                                    It doesn't matter what the value is in Java: primitive or address(roughly) of object, it is ALWAYS passed by value.



                                                    If a Java object "behaves" like it is being passed by reference, that is a property of mutability and has absolutely nothing to do with passing mechanisms.



                                                    I am not sure why this is so confusing, perhaps because so many Java "programmers" are not formally trained, and thus do not understand what is really going on in memory?





                                                    share














                                                    A few corrections to some posts.



                                                    C does NOT support pass by reference. It is ALWAYS pass by value. C++ does support pass by reference, but is not the default and is quite dangerous.



                                                    It doesn't matter what the value is in Java: primitive or address(roughly) of object, it is ALWAYS passed by value.



                                                    If a Java object "behaves" like it is being passed by reference, that is a property of mutability and has absolutely nothing to do with passing mechanisms.



                                                    I am not sure why this is so confusing, perhaps because so many Java "programmers" are not formally trained, and thus do not understand what is really going on in memory?






                                                    share













                                                    share


                                                    share








                                                    answered Dec 26 '09 at 20:19


























                                                    community wiki





                                                    Rusty Shackleford









                                                    • 1




                                                      +1. What C does support, is treating references (which C calls pointers) as first-class values, and then passing them by value.
                                                      – Jörg W Mittag
                                                      Sep 7 '10 at 22:02






                                                    • 1




                                                      Yeah, in C you can create pointers not only on objects, but on arbitrary variables - so you can easily simulate "call-by-reference" of any variable. In Java this works only for variables which have a surrounding object, which you can give.
                                                      – Paŭlo Ebermann
                                                      Feb 3 '11 at 1:27














                                                    • 1




                                                      +1. What C does support, is treating references (which C calls pointers) as first-class values, and then passing them by value.
                                                      – Jörg W Mittag
                                                      Sep 7 '10 at 22:02






                                                    • 1




                                                      Yeah, in C you can create pointers not only on objects, but on arbitrary variables - so you can easily simulate "call-by-reference" of any variable. In Java this works only for variables which have a surrounding object, which you can give.
                                                      – Paŭlo Ebermann
                                                      Feb 3 '11 at 1:27








                                                    1




                                                    1




                                                    +1. What C does support, is treating references (which C calls pointers) as first-class values, and then passing them by value.
                                                    – Jörg W Mittag
                                                    Sep 7 '10 at 22:02




                                                    +1. What C does support, is treating references (which C calls pointers) as first-class values, and then passing them by value.
                                                    – Jörg W Mittag
                                                    Sep 7 '10 at 22:02




                                                    1




                                                    1




                                                    Yeah, in C you can create pointers not only on objects, but on arbitrary variables - so you can easily simulate "call-by-reference" of any variable. In Java this works only for variables which have a surrounding object, which you can give.
                                                    – Paŭlo Ebermann
                                                    Feb 3 '11 at 1:27




                                                    Yeah, in C you can create pointers not only on objects, but on arbitrary variables - so you can easily simulate "call-by-reference" of any variable. In Java this works only for variables which have a surrounding object, which you can give.
                                                    – Paŭlo Ebermann
                                                    Feb 3 '11 at 1:27










                                                    up vote
                                                    22
                                                    down vote













                                                    To make a long story short, Java objects have some very peculiar properties.



                                                    In general, Java has primitive types (int, bool, char, double, etc) that are passed directly by value. Then Java has objects (everything that derives from java.lang.Object). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.



                                                    Does this sound strange and confusing? Let's consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. void foo(int x) passes an int by value. void foo(int *x) is a function that does not want an int a, but a pointer to an int: foo(&a). One would use this with the & operator to pass a variable address.



                                                    Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: void foo(int &x) is called by foo(a), where the compiler itself knows that it is a reference and the address of the non-reference a should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.





                                                    share























                                                    • I think it is very close to my understanding of Java object and its reference. Object in Java is passed to a method by a reference copy (or alias).
                                                      – MaxZoom
                                                      Feb 11 '15 at 5:58















                                                    up vote
                                                    22
                                                    down vote













                                                    To make a long story short, Java objects have some very peculiar properties.



                                                    In general, Java has primitive types (int, bool, char, double, etc) that are passed directly by value. Then Java has objects (everything that derives from java.lang.Object). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.



                                                    Does this sound strange and confusing? Let's consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. void foo(int x) passes an int by value. void foo(int *x) is a function that does not want an int a, but a pointer to an int: foo(&a). One would use this with the & operator to pass a variable address.



                                                    Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: void foo(int &x) is called by foo(a), where the compiler itself knows that it is a reference and the address of the non-reference a should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.





                                                    share























                                                    • I think it is very close to my understanding of Java object and its reference. Object in Java is passed to a method by a reference copy (or alias).
                                                      – MaxZoom
                                                      Feb 11 '15 at 5:58













                                                    up vote
                                                    22
                                                    down vote










                                                    up vote
                                                    22
                                                    down vote









                                                    To make a long story short, Java objects have some very peculiar properties.



                                                    In general, Java has primitive types (int, bool, char, double, etc) that are passed directly by value. Then Java has objects (everything that derives from java.lang.Object). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.



                                                    Does this sound strange and confusing? Let's consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. void foo(int x) passes an int by value. void foo(int *x) is a function that does not want an int a, but a pointer to an int: foo(&a). One would use this with the & operator to pass a variable address.



                                                    Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: void foo(int &x) is called by foo(a), where the compiler itself knows that it is a reference and the address of the non-reference a should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.





                                                    share














                                                    To make a long story short, Java objects have some very peculiar properties.



                                                    In general, Java has primitive types (int, bool, char, double, etc) that are passed directly by value. Then Java has objects (everything that derives from java.lang.Object). Objects are actually always handled through a reference (a reference being a pointer that you can't touch). That means that in effect, objects are passed by reference, as the references are normally not interesting. It does however mean that you cannot change which object is pointed to as the reference itself is passed by value.



                                                    Does this sound strange and confusing? Let's consider how C implements pass by reference and pass by value. In C, the default convention is pass by value. void foo(int x) passes an int by value. void foo(int *x) is a function that does not want an int a, but a pointer to an int: foo(&a). One would use this with the & operator to pass a variable address.



                                                    Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation: void foo(int &x) is called by foo(a), where the compiler itself knows that it is a reference and the address of the non-reference a should be passed. In Java, all variables referring to objects are actually of reference type, in effect forcing call by reference for most intends and purposes without the fine grained control (and complexity) afforded by, for example, C++.






                                                    share













                                                    share


                                                    share








                                                    edited May 4 '14 at 9:33


























                                                    community wiki





                                                    3 revs, 2 users 65%
                                                    Paul de Vrieze













                                                    • I think it is very close to my understanding of Java object and its reference. Object in Java is passed to a method by a reference copy (or alias).
                                                      – MaxZoom
                                                      Feb 11 '15 at 5:58


















                                                    • I think it is very close to my understanding of Java object and its reference. Object in Java is passed to a method by a reference copy (or alias).
                                                      – MaxZoom
                                                      Feb 11 '15 at 5:58
















                                                    I think it is very close to my understanding of Java object and its reference. Object in Java is passed to a method by a reference copy (or alias).
                                                    – MaxZoom
                                                    Feb 11 '15 at 5:58




                                                    I think it is very close to my understanding of Java object and its reference. Object in Java is passed to a method by a reference copy (or alias).
                                                    – MaxZoom
                                                    Feb 11 '15 at 5:58










                                                    up vote
                                                    21
                                                    down vote













                                                    Java passes parameters by VALUE, and by value ONLY.



                                                    To cut long story short:




                                                    For those coming from C#: THERE IS NO "out" parameter.



                                                    For those coming from PASCAL: THERE IS NO "var" parameter.




                                                    It means you can't change the reference from the object itself, but you can always change the object's properties.



                                                    A workaround is to use StringBuilder parameter instead String. And you can always use arrays!





                                                    share























                                                    • I think you nailed it by saying you can't change the reference from the object itself
                                                      – sakhunzai
                                                      Mar 30 '17 at 5:41










                                                    • So an object can be changed by using its public interfaces but could not be replace with sth else i.e deference and by this java achieves best of both worlds
                                                      – sakhunzai
                                                      Mar 30 '17 at 6:00















                                                    up vote
                                                    21
                                                    down vote













                                                    Java passes parameters by VALUE, and by value ONLY.



                                                    To cut long story short:




                                                    For those coming from C#: THERE IS NO "out" parameter.



                                                    For those coming from PASCAL: THERE IS NO "var" parameter.




                                                    It means you can't change the reference from the object itself, but you can always change the object's properties.



                                                    A workaround is to use StringBuilder parameter instead String. And you can always use arrays!





                                                    share























                                                    • I think you nailed it by saying you can't change the reference from the object itself
                                                      – sakhunzai
                                                      Mar 30 '17 at 5:41










                                                    • So an object can be changed by using its public interfaces but could not be replace with sth else i.e deference and by this java achieves best of both worlds
                                                      – sakhunzai
                                                      Mar 30 '17 at 6:00













                                                    up vote
                                                    21
                                                    down vote










                                                    up vote
                                                    21
                                                    down vote









                                                    Java passes parameters by VALUE, and by value ONLY.



                                                    To cut long story short:




                                                    For those coming from C#: THERE IS NO "out" parameter.



                                                    For those coming from PASCAL: THERE IS NO "var" parameter.




                                                    It means you can't change the reference from the object itself, but you can always change the object's properties.



                                                    A workaround is to use StringBuilder parameter instead String. And you can always use arrays!





                                                    share














                                                    Java passes parameters by VALUE, and by value ONLY.



                                                    To cut long story short:




                                                    For those coming from C#: THERE IS NO "out" parameter.



                                                    For those coming from PASCAL: THERE IS NO "var" parameter.




                                                    It means you can't change the reference from the object itself, but you can always change the object's properties.



                                                    A workaround is to use StringBuilder parameter instead String. And you can always use arrays!






                                                    share













                                                    share


                                                    share








                                                    edited Feb 11 '17 at 18:52


























                                                    community wiki





                                                    2 revs, 2 users 71%
                                                    Christian













                                                    • I think you nailed it by saying you can't change the reference from the object itself
                                                      – sakhunzai
                                                      Mar 30 '17 at 5:41










                                                    • So an object can be changed by using its public interfaces but could not be replace with sth else i.e deference and by this java achieves best of both worlds
                                                      – sakhunzai
                                                      Mar 30 '17 at 6:00


















                                                    • I think you nailed it by saying you can't change the reference from the object itself
                                                      – sakhunzai
                                                      Mar 30 '17 at 5:41










                                                    • So an object can be changed by using its public interfaces but could not be replace with sth else i.e deference and by this java achieves best of both worlds
                                                      – sakhunzai
                                                      Mar 30 '17 at 6:00
















                                                    I think you nailed it by saying you can't change the reference from the object itself
                                                    – sakhunzai
                                                    Mar 30 '17 at 5:41




                                                    I think you nailed it by saying you can't change the reference from the object itself
                                                    – sakhunzai
                                                    Mar 30 '17 at 5:41












                                                    So an object can be changed by using its public interfaces but could not be replace with sth else i.e deference and by this java achieves best of both worlds
                                                    – sakhunzai
                                                    Mar 30 '17 at 6:00




                                                    So an object can be changed by using its public interfaces but could not be replace with sth else i.e deference and by this java achieves best of both worlds
                                                    – sakhunzai
                                                    Mar 30 '17 at 6:00










                                                    1 2
                                                    3
                                                    next




                                                    protected by Nick Craver Jun 24 '11 at 18:08



                                                    Thank you for your interest in this question.
                                                    Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                    Would you like to answer one of these unanswered questions instead?



                                                    這個網誌中的熱門文章

                                                    Xamarin.form Move up view when keyboard appear

                                                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                                    Anylogic : not able to use stopDelay()