Is Java "pass-by-reference" or "pass-by-value"?

5 595

2 588

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?

user4315

Posted 2008-09-02T20:14:29.270

Reputation: 2 340

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.)

– None – 2011-12-15T06:12:03.130

@Gravity: Related: http://stackoverflow.com/questions/8113781/what-exactly-does-pass-by-reference-mean

– Mechanical snail – 2012-08-06T12:59:25.910

There is a very good answer by pgras in this thread: http://stackoverflow.com/questions/589919/does-java-pass-by-reference?lq=1

– mark – 2012-10-18T09:25:35.333

Of course Java passes all the objects by reference! For the blog mentioned in the question, the foo(Dog d) is just creating a new object and making d pointing to the new address (d originally referred to the object which is also referred by aDog -- This is so-called "pass-by-reference"). It is changing the pointer, the original object is still in its place without any change. The point is there is no copy of the value of object at all, it only copies the reference value. – shuangwhywhy – 2013-01-15T17:58:19.947

1And you cannot say it is "pass-by-value" just because the method doesn't change the pass-in value, you must check is any VALUE COPY there. – shuangwhywhy – 2013-01-15T18:24:53.040

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 – 2013-11-12T20:58:58.270

22I think the confusion is "pass by reference" versus "reference semantics". Java is pass-by-value with reference semantics. – spraff – 2014-03-27T13:54:30.003

3I usually use the term pass-by-pointer. Sure, the pointer is passed by value, but, after all, the pointer isn't what anyone cares about. This makes it clear that the pointer (not the object) is being copied, that mutating the pointed object will be visible to the caller, and that changing what the copy is pointing at will not be. – Kevin – 2014-08-10T23:47:45.507

a lot of the answers here are wrong or misleading. we should just forget the semantics and demonstrate the properties of a particular language with examples. – Alexander Mills – 2014-09-23T03:07:30.757

Java is focused towards code maintainability so they didn't include featuers that made code harder to maintain. For the most part these features allwed people to hand-optimize code where the compiler couldn't, but the Java runtime allows an alternative so that featuers like free pointers and references just don't give that much of a performance boost to make them worth the destabilizing effect. C/C++ offer a different path--you don't have to trust a runtime and have more control over the hardware. Both are valid, but pass by ref and pointers would be really bad ideas in java. – Bill K – 2014-09-24T19:01:45.927

If java is "pass by value" then why the result of below program is : //0 //1 //2 ( may be you are using "String" which is an immutable class ) public class Newfile{ public int x=0; }public class HelloWorld{
public static void changeX(Newfile tr){ tr.x++; } public static void main(String []args){ Newfile trf = new Newfile(); System.out.println(trf.x); changeX(trf); System.out.println(trf.x); changeX(trf); System.out.println(trf.x); } }
– Anand M Arora – 2015-03-18T11:56:40.440

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. – None – 2015-03-23T13:44:28.653

2@anandmarora, in your example, the changeX() method is taking a reference as a parameter. That reference is passed to it as a value. Consider what would happen if your method was instead defined like this: void changeX(Newfile tr){ tr = new Newfile();} If java were PBR, then the method calling changeX() would have it's object switched out entirely. Because it is PBV, the nothing happens after changeX() returns. – None – 2015-03-23T13:57:10.160

Never understood the confusion about the Java pass-by-eference vs. pass-by-value confusion (c/ c++ background, now a c#-programmer). Calling a Methode with a pointer passes the pointer and allows you to change the underlying object. Passing a pointer to a pointer allows you to change the original pointer to an object. Java have no concept of "pointer of pointers" and that's it. (C++-references are just obscufacted pointers) – Peter Schneider – 2015-03-24T22:39:59.910

2Some concepts are just a bit difficult, and we are not helped by languages trying to make them "safe" or to "hide" them. This Question has over 3/4 of a MILLION Views and 55 Answers... The real answer should be: "Draw a diagram for yourself and keep looking at it until you understand." There are much harder issues than this, and if you can't get it fairly easily, it does not bode well for you as a programmer. – None – 2015-10-21T19:14:54.467

3The Java Language Specification defines a "reference" as a pointer. Also, the definitions of "call by value" and "call by reference" in computer science are not ambiguous. "Call by value" means that changes to an argument in the method are not visible to the caller; "call by reference" means that they are not. The stuff about "it depends on how you define 'reference'" is irrelevant and inapplicable. Java method calls are unambiguously call by value. – Lew Bloch – 2016-01-09T21:01:46.950

6

>

  • Java is pass-by-value.
  • For primitives, you pass a copy of the actual value.
  • For references to objects, you pass a copy of the reference (the remote control). http://www.javaranch.com/campfire/StoryPassBy.jsp
  • – Max – 2016-03-10T16:47:24.150

    2Look at the next answer, which really answers the question: Java does BY-VALUE. Period. – Michael – 2016-06-15T19:04:39.293

    It's pass-by-value. So Java will COPY an object that you hand as a parameter. But, the references to object (memory addresses) inside that object are values, so are copied and still point to the same memory. So, if you change a referenced object contained INSIDE of an object that you handed as a parameter, it will change the memory and thus the original object. Whereas if you just change the object handed as a parameter, the original object is unchanged. Primitives (ints, floats, arrays, etc) are copied as values and don't have this style of references. – Araymer – 2016-11-11T17:04:15.263

    How did you assume pass-by-reference ? – Manish Shrivastava – 2017-01-18T13:57:36.137

    As a pure Java programmer, reference is not confusing, but pass by is. What is pass-by? – WesternGun – 2017-04-26T07:53:21.023

    Java always pass arguments by value, the copy would be either a reference or a variable depending on the actual variable type. Check out this article to find a practical example and tips http://programmergate.com/java-pass-reference-pass-value/

    – Hussein Terek – 2017-07-29T14:00:55.140

    2java is reference based and mostly it acts call by reference. – A.Shaheri – 2017-07-30T07:33:15.727

    578I 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 – 2011-07-30T07:23:05.650

    http://javadude.com/articles/passbyvalue.htm – Christophe Roussy – 2018-02-20T10:24:04.623

    Remember this: Roses are red, violets are blue, if it's Java, it's pass by value. – sannidhi – 2018-05-12T15:17:43.153

    This is surely the question with the most answers that are either useless or simply plain wrong, and still have many upvotes. – Ingo – 2018-05-21T00:11:29.033

    Answers

    4 940

    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")).

    erlando

    Posted 2008-09-02T20:14:29.270

    Reputation: 6 031

    19@ubershmekel - no, that's not correct. "Passing references by value" in Java is exactly the same as "passing a pointer by value" in C++. Passing by reference in C++ allows the called function/method to actually change the variable used to pass the value. Passing by value always allows the called function/method to read-and-follow a pointer passed by value... – Scott Stanchfield – 2012-01-26T22:15:51.813

    17Java modifies the meaning of 'pass by reference' from languages like C/C++. In C/C++, the term 'pass by reference' means passing the value of the variable's address (this is what a pointer is!), not the variable itself. You makes changes to the object/variable at 'xyz' address in memory (you change the original). This done when changing the original is intended (why pass the whole thing?). Passing by value passes a copy of the actual object/variable to preserve the original. Java doesn't give an option. OO Objects are passed by reference (in C/C++ terms), primitives are passed by value. – Bill Rosmus – 2012-05-08T16:02:07.930

    1Think of methods params as local variables initialized with a value. – sergiofbsilva – 2012-05-30T19:32:50.843

    @erlando, can we have a similar example of distinction for Array Objects? – pop stack – 2012-06-03T09:17:04.510

    4beware however that integral types are passed by value and not by reference. Also immutable types are passed by reference but "kinda" works as passing them by value: the most common example would be String. This allow for internal space optimization of immutable objects. – Lorenzo Boccaccia – 2008-11-26T17:50:54.243

    14@BillR - C was strictly pass-by-value; C++ added pass-by-reference semantics, but by no means was it the first language to implement those semantics. The term "pass-by-reference" has a very specific meaning, and Java simply does not implement it. Keep the terms simple and to what they actually mean and its much easier to understand and explain. Java passes everything by value, including pointers. (It's also easiest if you simply avoid using the term "reference" at all in Java... they're pointers...) – Scott Stanchfield – 2012-08-30T04:44:34.180

    6@Scott Stanchfield when I pass by value from method/function 1 to method/function 2 I should see a copy made of the value in 1 and sent such that if I change the value in 2 I do not see a change in 1. That is not how it works in Java. I have done, and just did it a few minutes ago, passed a variable to another method, and had it updated and had it update the value in my calling method. At this time I wanted this behaviour. But sometimes this can be a cloudy issue and it can cause this effect when one is not looking for it. This is indeed passing by memory reference. – Bill Rosmus – 2012-08-30T05:32:06.143

    5

    @Scott Stanchfield and C was not strictly pass by value. Look at the pass by value and pass by reference links here: http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcfpv.htm

    Look at the link there on pass by value. This is how other programming languages define it. What Java does is call by reference because what you do in the second function (method) does change the variable in the calling/first function. Java can pee be on my leg and tell me it's raining, but it doesn't make it so. Java has co-opted the term pass by value.

    – Bill Rosmus – 2012-08-30T05:54:16.393

    5@BillR Not so. Java is pass by (new L)value. The terms pass by reference/(new L)value/macro are terms defined (for example) by the Scott-Strachey theory of programming languages and Java is definitely passing by (new L)value. Your little test example didn't update the caller's variable but instead probably updated the object referenced by the caller's variable. – Steve Powell – 2012-09-11T15:30:22.910

    341But 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 – 2008-09-11T06:55:48.503

    1Basically a java reference passed as a function parameter is like a C++ pointer passed as a function parameter (not pass-by-reference; C++ convention of by-reference), when you modify it inside the function, you are modifying a local variable, neither the referenced object, nor the passed reference .. – Khaled.K – 2013-03-24T14:18:13.510

    Really its a dilemma in the terminology.

    Consider the same example in terms of c++, for which everybody hopefully agree its 'passed by reference' (or its reference passed by value?) void foo(Dog & d) { d.name.equals("Max"); // true // d = *(new Dog("Fifi")); //<- C++ does not allows this //So what is point in in arguing passed by reference or not } – shakthi – 2013-06-01T17:10:55.657

    1In my heart, I'm with BillR's crowd on this one... however, to my peeps: consider that the original object pointer is not lost, but retained after the function exits. That's why they're making the distinction--they're saying a COPY of the reference/pointer value is made when passed to the function, which then can be over-written. I still don't like calling this pass-by-value, but some guy with some theory of programming says it is, so we all have to agree. – Angelo – 2013-06-08T07:53:57.253

    5@BillR Incredible that despite the utterly clear answer you're still arguing against it. Java passes only pointers. A pointer is an opaque type that we can think of as being a primitive number. This number is passed by value. So Java passes pointers, and those pointers are pass by value. – Mike Braun – 2013-11-30T17:08:37.193

    5@MikeBraun if you actually studied programming using pointers (like using the C language) you will understand that when you use pointers as a function argument you are "passing by reference". You are referring to a specific place in memory using a pointer. i.e. By pointing to the memory location you are making a reference to it. How many ways do you need it stated to understand the concept? And have you neglected to look at the arguments in my favour, or just not understood them? Or worse, didn't understand them because you didn't want to understand them? – Bill Rosmus – 2013-12-09T01:38:31.810

    34@BillR I have a comp. sci master and learned programming in C and C++. I've build compilers and CPU emulators. I think I have a fair grasp of both language theory and low level system dynamics. I can without a shadow of doubt say that you are wrong. Passing a pointer is NOT pass by reference. The pointer itself is a numeric that you can pass either by value or by reference. In C++ you can do both. In Java you can only pass by value. It has been shown to you that you can't change the variable holding the pointer. You can only follow the pointer, but that does not change the calling method. – Mike Braun – 2013-12-10T17:42:57.713

    5So passing a pointer by reference means that if you then re-assign that reference (within the block of code that you have passed it to), you are changing that actual pointer value, effectively severing it from the original object that it pointed to, rendering that object eligible for garbage collection (if no other pointers point to it).And this you can't do in Java because you are never passing the reference of the pointer, only a copy of the value of the pointer. Reassignment of the copy only points that copy elsewhere. The original pointer remains untouched. – Psyrus – 2014-01-11T01:02:21.377

    Shouldnt the first snippet follow the second one? Or am I seeing this the wrong way? – KodeSeeker – 2014-02-07T19:14:01.690

    6Sounds 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 – 2014-03-12T17:39:13.207

    220Isn'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 – 2008-09-08T14:58:53.407

    266@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 – 2009-02-12T23:02:20.903

    3@JohnStrickler I have seen a recent example of my colleague 'nulling' the object arguments at the end of the invoked method, and expecting to see it 'nulled' in the caller. So, you are quite right that it may be 'purism', but many people still ignore it (and still they produce lines of code). – Leonardo – 2014-05-08T12:05:05.033

    3You can think of object declarations in Java as C/C++ pointers (they reference objects, they can be null, etc.). People claim Java is entirely pass-by-value because these references themselves are passed by-value (in the same way that C/C++ pointers are passed by value - the pointer is copied, but the pointed-to object is not). So if you consider passing pointers in C/C++ to be passing by-reference, then Java is pass-by-reference. The exception is primitives like int, which are always passed-by-value (copied) in Java. – orfdorf – 2014-10-23T04:13:24.560

    261My 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 – 2010-10-20T16:38:55.607

    @erlando I tried to update the answer to reflect your comment. Please review, I don't want to mislead people on such a question. :)

    – ArtB – 2014-11-27T16:53:08.340

    2Having a C/C++ background, I think of it as pass by value: func(Dog d), pass by reference: func(Dog &d), and pass by pointer: func(Dog *d). Java behaves to me like pass by reference, even though in compiler-speak that implies a caller's object location in memory can be replaced, aka pass by pointer. Whenever I hear Java's objects are passed by value, it makes me think there is a shallow copy when there isn't. So it's a C++ reference v. compiler-speak pass by reference that seems conflicting. – Shawn – 2015-02-20T03:32:15.810

    3Só Java passes, by value, the reference to the object? – Tito – 2015-06-18T00:11:33.377

    3@BillR: "Java modifies the meaning of 'pass by reference' from languages like C/C++..." and there is the root of your misunderstanding. Java doesn't get to "modify the meaning of 'pass by reference'" any more than I do. The term already has a meaning in computer science. It's useless and confusing to try to persuade people that "pass by reference" has different meanings in different languages. – DavidS – 2015-08-04T21:22:29.443

    1@BillR Pass by reference: void f(std::string & s) { s = std::string("A different string."); } Pass pointer by value: void f(std::string * s) { s = new std::string("A different string."); } If you take the address of a string and pass it to the second function, you aren't changing the original, but if you pass it by reference to the first, you are. – Impossibility – 2015-08-19T23:47:35.263

    5@Shawn Java does not behave like the C++ func(Dog &d). If you reassign d in the body of the function func(Dog &d), the object that was used to call the function will also be reassigned. It behaves more like func(Dog *d). If you reassign the pointer in the body of the function, the original pointer passed to the function won't be reassigned. – PC Luddite – 2015-08-31T20:11:42.377

    1Nobody has mentioned that C# does implement pass by reference with the use of the ref keyword. – PC Luddite – 2015-08-31T20:20:50.357

    3Your point might be clearer if the name passed to the constructor was different than the name used in the foo method. – Ishmael – 2011-02-02T21:10:46.840

    127What'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 – 2011-02-09T09:46:44.320

    public class trial { static trial t_ = new trial(); public class trial1 { private String s = "hmm"; }

    public static void main(String[] args) { trial1 t = t_.new trial1(); foo(t); System.out.println("main: " + t.s); }

    private static void foo(trial1 t) { t = t_.new trial1(); //special line t.s = "noo"; System.out.println("foo: " + t.s); } }

    If i remove the line tagged as special line, both the syso's are returning the updated value. Does that mean we are sending a pointer of the trial1 object to foo?

    Please use a formater to look at the code. – Revanth Kumar – 2016-01-08T22:48:13.280

    @RevanthKumar - Hard to tell from the formatting; I assume your special line is the "t = t_.new trial1()" line? If so, then yes. You have a pointer passed to foo. If the special line is run, the parameter t is changed to point to a new trial object, and the string in that new trial1 is changed. If that line is removed, foo follows the pointer to the trial1 passed in and changes its string. – Scott Stanchfield – 2016-01-15T14:14:55.790

    2I'm sorry, but the fact that you can retarget the reference does not change the fact that what you received was a reference to the actual object. Basically, the entire problem with this definition is that it means there is no such thing as pass by reference in any language, ever. All languages are pass by value according to this reasoning. – Cdaragorn – 2016-05-06T20:34:48.473

    @Cdaragorn Pass-by-value means that you pass the value of a variable. Pass-by-reference basically means that you pass the variable itself. The point is that this happens implicitly, i.e. you can call foo(x) instead of having to call foo(&x) and dereference x in foo. It's this dichotomy that makes the difference, not the type of value that is passed. Unfortunately many people only focus on just that, which inevitably creates confusion. – a better oliver – 2016-05-09T13:24:06.973

    2@zeroflagL That's the problem. It is impossible to ever pass the variable itself. In your example (foo(&x)), you aren't passing x. Your passing a reference to x. By that definition, there is no such thing as pass by reference because it can never be done. – Cdaragorn – 2016-05-12T15:31:29.757

    @Cdaragorn "In your example (foo(&x)) ... Your passing a reference to x" Um, that's the point I was making. – a better oliver – 2016-05-13T06:47:28.767

    3Ok, so foo(&x) is no different than foo(*x). They both pass a reference by value, so by Java's definition they are both pass by value. The whole point of pass by reference was never how the actual value you got passed was passed, it's about how the object the user wants you to have was passed. This definition makes that meaningless. It is completely impossible to pass anything by any means other than by value. – Cdaragorn – 2016-05-16T20:42:29.673

    3@izb the fact that pointers to objects are copied is different from the notion that objects are passed by reference. Because they are not passed by reference, their reference is copied. – EpicPandaForce – 2016-06-06T10:51:10.023

    1This can cause SERIOUS problems. Because when you pass an object as parameter in a function, you don't know wether it will be modified by the user who use the function. – Kai Wang – 2016-10-25T18:58:44.773

    I would suggest to avoid using those terms altogether within a Java context. Just known how it really works in Java — this example did a great job doing so. – MC Emperor – 2017-01-07T11:58:55.893

    or we can say it is not pass by reference but it is object's reference passed by value. – jayendra bhatt – 2017-01-19T18:01:13.813

    I am Little confused. Can Anyone explain this concept of array being pass by reference? https://gist.github.com/shah-smit/0506d70f7a48b70eeddbe00b59ce6a84

    – Smit – 2017-03-07T10:03:53.337

    3

    BlueRaja, not anything that would hold up in court, that is from my recollection which may be flawed, but some evidence can be found right here: http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.3.1

    – Prof. Falken – 2011-06-03T22:56:07.100

    During Compile time , java behaves as pass by reference.during runtime it's pass by value. – Jajikanth pydimarla – 2017-03-21T16:24:44.850

    2Is it safe to say that Java uses semi references because modification mutates the original object? – peter – 2017-04-01T17:39:44.840

    @peter no, that is not correct. That is passing a copy of a pointer to a selectively mutable memory location. Mutating the value stored there is a side effecting operation that is observable to both the caller and the callee. – Aluan Haddad – 2017-04-29T03:20:21.077

    1I like to think of pass-by-value (As pertains to parameters of functions) as meaning that every function makes a local copy of the objects passed. In general, relying on a satellite method do it's job on some larger state seems more nebulous than explicitly defining the state passed and returned. – dwerner – 2011-06-21T20:03:02.483

    4Java is "pass-by-voodoo-doll", when an object is passed while calling a method, the method actually receives a voodoo-doll using which you can control the actual object, but can't replace the object altogether. – Satyendra Kumar – 2017-06-24T16:09:26.233

    2Long story short, the problem is using the same word for "reference to an object" vs. "reference to a variable" – Kos – 2017-07-06T12:22:09.883

    2@Shawn, I think you'd agree that Java is pass-by-value if you consider a Java Dog implicitly corresponding to a C++ Dog *. It makes sense if you consider the fact that all all initializations have new in it, like so: Dog d = new Dog(); A variable in Java can never hold an object. – aioobe – 2017-07-20T00:11:33.970

    2I had to downvote this answer because it is self-contradicting. The answers, and even some of the supporting commenters, support the idea that "It all depends on how you define a reference, so this is merely arguing semantics, not language mechanics" when they say that it is not "pass by reference" and then go on to say that "we are passing the reference to it." Answer and comments supporting "this is not pass by reference" both use this wording. Again, direct quote from answer: "we are passing the reference to it." (ironically, emphasis is answerer's, not mine) – Aaron – 2017-08-02T14:58:09.967

    Great explanation!!! I would add that in case of Java RMI calls, the method receives a full serialized copy of the parameter, not the value of the reference. – Nicolas C – 2017-08-24T13:48:01.447

    1"When we pass the value of an object, we are passing the reference to it." Then, Java is a pass-by-reference language, I think... – Hiroki – 2017-09-16T07:59:19.870

    Then why even have the two god damn terms? Yes, pass-by-reference will deal with values at some level but you don't have to abstract concepts to the n-th degree! – RecursiveExceptionException – 2017-10-17T00:07:46.580

    I would say that, since Java is claiming to be Object Oriented, it is objects people care about, and objects people are interested in passing. The interesting thing most new developers in Java must realise, is that the only way to pass an object, is by passing a copy of the reference, giving pass by reference semantics for objects, which is what matters to 99% of people who ask this question. If the references themselves were passed by reference, it would be very confusing, and next to impossible to use the language. – morten – 2017-10-26T08:53:40.487

    2All this debate is actually because guys at Sun made a terrible naming mistake.

    They used the name REFERENCE instead of POINTERS.

    Well it was not actually a mistake. Acording to a guy, who worked with another guy from the original Sun team, the usage of reference word instead of pointers was requested by the sale department.

    The sale department wanted to push Java as a secure language, and one of the strong point they where advertising was "Java's advantages that it does not allow pointer arithmetic as C++ does". – Grigore Madalin – 2017-11-12T08:00:27.997

    1The guy knwon by my guy, like the rest of the Sun team had to create this big lie. They knew what pointers are. They new what references are. But the money demanded the terms switch.

    Because of this, today many Java programmers don't have a clue what a reference is because they learned the wrong term. Originally a "reference" strictly means an alias to a variable passed as a parameter. The reference word describe the method of passing a parameter to a function. Sun team redefined the "reference" term because Sun wanted more success for the Java language and more money in the pocket. – Grigore Madalin – 2017-11-12T08:01:34.053

    1@erlando i really think in oder to improve your answer and make it complete you should mention this "reference" term meaning alteration that Java use. Unfortunately is very hard to teach Java programmers that they where told the wrong term. But this is the truth. At the end the winners write the history. Java rewrote the reference definition and people believe them simply because they win a lot of users. – Grigore Madalin – 2017-11-12T08:08:41.253

    12Isn't saying "object references are passed by value" just what people mean when they say "pass by reference"? I mean you wouldn't call void foo(int& a) { a = 5; } "pass by value" in C++, but it's exactly the same as Java. – Timmmm – 2011-08-02T09:58:33.243

    1We can just treat the reference as an equivalence of pointer in c++. – Bohao LI – 2017-12-06T19:42:40.657

    9Java is pass-by-copy-of-the-variable-value. There is no difference in passing primitives or Objects! The only difference is that the primitive variable contains its value directly while an object variable contains a bit value that helps the JVM to find the Object in the Heap. Also, in both cases these reference values are copied before being given to the method. Finally, please don't mention p....... while talking about Java, not even to say that it's incorrect to do that! – Gevorg – 2011-08-12T01:31:43.507

    5Yes Timmmm, I think erlando's counter-example is wrong in the context of C++ references. It's true to say that in Java they're "passing references by value", but it means exactly the same thing as a C++ programmer would expect when "passing by reference". – ubershmekel – 2011-08-18T17:01:01.990

    It seems that essentially java is pass-by-value for primitives and pass-by-reference for objects – huangzonghao – 2018-03-24T03:10:50.157

    1As this answer points out "passing by reference" is different than "passing a reference" (which can still be done in a pass-by-value language like Java). A lot of commenters have failed to grasp the difference. – ikegami – 2018-03-30T09:26:49.053

    Re "What's confusing is that object references are actually pointers", Well yeah. References are pointers on which one can't do pointer arithmetic. – ikegami – 2018-03-30T09:28:17.577

    Can someone explain me this difference: if I have a method void changeInt(int myInt){ /...} where myInt is set to some new value, it is pass by value, so after passing some integer, the value is the same it was before. If I then define a method (let's assume I have a class ListNode that should represent a linked list) void changeHead(ListNode myHead){ myHead.value = 155; myHead = myHead.next;}, then after passing myHead to changeHead, its value has changed to 155, but the head is still the initial head and not head.next . I somehow can not match this two examples to find a general rule. – Giacomo – 2018-07-17T08:25:53.833

    Even though the answer itself is correct I don't think it's good to say that JAVA is always "call by value" because the distinction between "call by reference" and "call by value" is still necessary. That said the example will be remote method calls of EJB's vs. method calls of local EJB's. To explain in a better way how the method calls happen in the JavaEE world a distinction of these is in my opinion very helpful. Even Oracle uses this distinction. See: [https://docs.oracle.com/cd/E24329_01/web.1211/e24368/classloading.htm#WLPRG312] (Application Classloading and Pass-by-Value or Reference)

    – the hand of NOD – 2018-08-01T12:38:08.050

    1erlando's line "If it were passed by reference, then the aDog.getName() in main would return 'Fifi' after the call to foo" will clear all this confusion that Java is pass by Value for primitive as well as for object. Few folks may think it as illusion. – pathe.kiran – 2018-08-18T18:34:21.987

    @SatyendraKumar This is an infuriatingly underrated comment. I got a good laugh. – spicypumpkin – 2018-09-12T17:13:38.990

    @Aaron Well, then how would you define a "true" pass-by-reference, where the original variable (not value) can be changed inside a function call? Java is pass-by-value where they pass the value of a reference, and I can't think of any good way to describe this in a simple pass-by-x lingo. – spicypumpkin – 2018-09-12T17:18:10.840

    1@Giacomo As the answer says, the function takes a reference to the value, so you can update the original value. But the variable that holds this reference has no connection to the variable outside of the function that refers to the same value. So when you assign a new value to the local variable inside the function, you simply overwrite whatever reference was passed to. – spicypumpkin – 2018-09-12T17:23:19.873

    @spicypumpkin First, I wouldn't create a definition. It annoys me when people think they need to redefine the English language when it is used to talk about a particular field. These are English words and have meaning whether you are talking about computers or anything else. So I wouldn't define it. Second, "pass by value where value is a reference" is so close to saying "pass by reference" that it can be said without confusion. In fact, it works so close to a C++ reference, biggest difference being reassignment, that I think people should look at it that way. – Aaron – 2018-09-13T15:42:01.847

    @Aaron The problem is that there is a confusion. As the examples show, the two passes show different behaviors that imho they require different definitions. Clearly, these "English words" aren't accurate enough to define these schemes. – spicypumpkin – 2018-09-13T16:04:06.720

    @spicypumpkin If you say so; maybe you've run into the need, in which case feel free to be specific. But this has never been a problem in conversation with other software engineers in my experience, not even when discussing compiler programming for JVM languages, which I think is where it would most likely be an issue if it were an issue. Since it hasn't been an issue (for me) in English language discussions of compiler construction for JVM languages, my aforementioned feelings will persist. – Aaron – 2018-09-13T16:23:36.307

    @Aaron I mean, sure, if you're within Java context it shouldn't matter. The confusion ensues because there are certain other languages that behave differently. And I think it's an important/necessary distinction for especially students like myself. – spicypumpkin – 2018-09-13T16:49:19.067

    @spicypumpkin The question itself that this answer is for is within the context of Java. I broadened it a little bit with my last comment though for the sake of my point: JVM languages involves more than just Java, and indeed the discussions I mentioned were not about Java but were about research into Java-like languages targeting the JVM. My last comment's point was just that I've never found it to be an issue in actual use. If you're a student though, by all means dig in and understand it at the lowest level. Even then however, I personally wouldn't strictly define 'pass-by-reference'. – Aaron – 2018-09-13T17:11:04.110

    Thats a really nice answer! – Spara – 2018-11-13T13:47:14.767

    2 720

    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.

    Scott Stanchfield

    Posted 2008-09-02T20:14:29.270

    Reputation: 25 367

    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 – 2011-12-30T18:30:02.083

    1I totally agree with you; however in the book "Sun Certified Associate Study Guide - 2009 Ed", on page 183, question number 10 of the "Self Test Answers" of Chapter 5 says this: "Objects are always passed to methods by reference. This means changes made to the object in the method will be reflected in the object in the code that invoked the method." I agree with you, but what answer should I choose for this Java Test? – Cacho Santa – 2012-01-12T01:47:21.687

    5Saying Java is pass by value is both meaningless and confusing. Everything on a computer is pass by value. In Java, when changing a passed-in array it changes the original array, so the array is not passed by value, it was passed by reference. The pointer was passed by value. It depends on the depth of abstraction and definition you use. In C++ when you change a pointer you are still accessing that pointer via a value, the memory location of it, but you would not call it pass by value. – Xonatron – 2012-01-26T14:40:11.477

    It's very confusing to those of us who really want to understand what is going on to make blanket statements such as "Java is pass by value" when it clearly contains results that appear to be pass by reference. To use such low levels of abstraction on newcomers to the language is confusing, and ultimately meaningless when you go too far: as I said before, everything is pass by value on a computer at the lowest level. Now, please point out where I am wrong as in my confusion at the moment I could very well be wrong. – Xonatron – 2012-01-26T14:41:59.870

    3@Matthew - "Pass by value" has a very specific definition in programming language design. Not all parameters are passed by value; some languages (like C++ and Ada) do in fact pass parameters by reference (if you use the & [C++] or "in out" [Ada] modifier on the formal parameter definition). – Scott Stanchfield – 2012-01-26T21:58:40.417

    @Matthew - Java does not, in fact, contain results that appear to be pass-by-reference. You cannot, from inside a method, change the value of a variable that was used as a parameter. (You can, of course, follow a pointer and change the contents of the object it points to, but that is not reference semantics; you're simply following a value). – Scott Stanchfield – 2012-01-26T22:01:17.207

    1@Matthew - Saying anything else to newcomers would be as incorrect as describing Java as a procedural language because they weren't familiar with object-oriented programming. If someone does not properly understand value vs. reference semantics, it's important to give them the proper understanding, especially if they later move to a language that does have reference semantics. (Imagine if you didn't understand it and assigned a parameter, like dog = new Dog(). In java, it doesn't change the external variable, but other languages might. Not knowing the difference causes confusion) – Scott Stanchfield – 2012-01-26T22:09:43.900

    @Scott, following the pointer and changing the contents means the same thing as passing by reference at a higher level. An array can be considered its contents. It's a matter of language and definition. I understand how it works fundamentally. Java's problem is that it hides the fundamentals to begin with: http://joelonsoftware.com/articles/ThePerilsofJavaSchools.html. I agree 100% with your desire to have everyone understand what is actually happening, and maybe your "rocking the boat" causes people to pay attention. I'm just noting that it matters on the level of abstraction you dive to.

    – Xonatron – 2012-01-27T13:45:41.347

    4@Scott, I guess this better explains my point: If you see someone accepting Java as pass by reference, you can show a piece of code that breaks that theory. But, also, if you see someone accepting Java as pass by value, I can show code that breaks that theory, based on their weak higher level understanding of "pass by value". The terminology is at fault here. I think the best answer to this question would be to describe each of the "pass by" methods along with proper naming conventions that segregate them. – Xonatron – 2012-01-27T13:47:49.300

    @ScottStanchfield, I referred to C++ because Java is its direct evolution. Regarding pointers, besides the NullPointerException there's nothing else left as you can see from the following White Paper http://java.sun.com/docs/white/langenv/Simple.doc2.html#4107 ! Also, even if I'm not an expert I believe that most JVMs use handles to objects and objects might be moved in the Heap while the reference value does not change (this shouldn't be happening in C/C++)! Still, I do not want to talk about JVMs implementation and I cannot believe that I just mentioned Java and 'Ps' in the same comment ;)

    – Gevorg – 2012-01-27T16:47:24.033

    Good points but you are still essentially wrong in your conclusion. Java does pass by reference. Just because it has a reduced instruction set that doesn't allow you to change where the pointer points, doesn't make it pass by value. You are still maintaining a reference to the original object, you do not have a copy of the object so that the original is not changed. The only time this is not true is with immutable objects and primitives. This is like being politically correct or using propaganda... just because you say a turd is a steak doesn't mean it still doesn't taste like ... – Bill Rosmus – 2012-05-08T16:11:39.260

    @BillR - not at all like propaganda or being politically correct... Computer language design has very precise meanings for pass-by-value and pass-by-reference. If you cannot change the actual thing passed (the pointer to the Dog, in these examples) it's pass-by-value. By your logic, C has pass-by-reference semantics (which it more obviously does not) – Scott Stanchfield – 2012-12-23T00:15:50.000

    @Scott Stanchfield Very good explanation. I will just add that when using RMI, references are managed separately so even if we update one instance in one side A (someDog.setName("NewName")) and then return immediately, it will not get updated in the other side B. I will explain it in detail later if I got the time. Regards. – Rodmar Conde – 2013-04-30T13:25:07.400

    1

    @RodmarConde - yep - check the "A Note on Remote Method Invocation (RMI)" section of my article: http://javadude.com/articles/passbyvalue.htm - the one that started this question. RMI calls have two modes: value and reference.

    – Scott Stanchfield – 2013-04-30T13:46:20.720

    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 – 2010-09-07T22:12:35.200

    1@Comptrol the pointer hasn't changed; its value is still 42. If it were pass-by-reference then it would change to the memory location of the new dog Fifi (which gets renamed to Rowlf, but the pointer wouldn't change a second time). Finally, if it were pass-by-reference, myDog would be called Rowlf after the method returned void. – Robert Grant – 2014-07-24T15:17:33.407

    When you say, "...it's still pointing to the original Dog." is it because whatever happened in foo() was done to the value of the pointer pointing to myDog and once that method is done, then it's out of scope? From my understanding, if we're passing in a reference to "Rover", I don't understand why the operations inside foo() doesn't affect "Rover". – JPL – 2014-08-26T05:06:50.897

    3I don't think we need another term. "Pass-by-value" covers this appropriately. Liskov rocks (I wonder if anyone ever said those exact words to her?), but "call by (object) sharing" adds nothing new. We could add a corresponding "Call by primitive" which also adds nothing new. I like to apply the KISS rule here... – Scott Stanchfield – 2010-10-28T20:49:33.933

    @JPL - in foo, line // AAA follows the pointer to the "Rover" dog and changes his name. line // BBB points the variable at a new dog, so anything else done with that variable doesn't affect the dog-formerly-known-as-Rover. After the method, myDog still points to the dog-formerly-known-as-Rover. – Scott Stanchfield – 2015-04-02T21:03:23.577

    122This is why the common refrain "Java doesn't have pointers" is so misleading. – Beska – 2009-04-02T17:52:18.680

    @ScottStanchfield I have always enjoyed this answer. I think that one thing which would really help, though, is if you had an addendum which dealt with a second method which accepted and reassigned a scalar. This is one of those topics I’ve taught a lot when dealing with JSSL (JS as a Second Language) devs. The dichotomy of modifying the contents of an object/list (which has side-effects out of scope, of course), versus reassigning the value of x in the outer scope, is the point where I find people go “aha!”. – Norguard – 2015-08-25T22:45:08.523

    1Of course the deeper answer as to why that’s proof of value passing (when the value of the complex object is clearly a reference, despite the scalar’s value being a copy of the scalar’s value) becomes less straightforward, but is hopefully an easier talk, thereafter. – Norguard – 2015-08-25T22:56:13.913

    Hmmm... I guess I assumed that what happens with primitives was obvious... I hadn't thought about it. I could actually start the article with an example of passing in an int and then move to the Dog example to show it's doing the same thing. I really need to update it with some pictures that show the heap and stack, too... Thanks for the suggestion! – Scott Stanchfield – 2015-08-26T22:26:59.247

    122You 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 – 2009-04-06T05:22:09.560

    2Looks like Java passes objects by a value of a reference to their value. – IllidanS4 – 2015-11-21T10:47:02.853

    One of the points in my article is that, what Gosling and Joy called "references" are pointers, from a programmer's point of view. (If it looks like a pointer and acts like a pointer, for all intents and purposes for the programmer, it's a pointer.) Their use of the term "reference" has caused all of the confusion over Java being pass-by-value. – Scott Stanchfield – 2016-01-15T14:08:07.413

    168Think 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 – 2009-04-23T13:06:40.847

    So you're saying that in line // BBB of foo(), myDog (still at address 42) now points to the dog at address 74? And that the original dog (now named Max) is still located at address 42, but when 42 is read it points to address 74. So if you cannot retrieve Max (let's say he's a retriever to confuse things) how does he still exist. Can you still retrieve the retriever? (serious question) – YoungCoconutCode – 2016-06-16T16:17:13.770

    Keep in mind that myDog is a pointer; it doesn't reside at 42 (it sits somewhere else in memory), it has value 42. When foo() is called, that 42 is passed in as parameter someDog. On // AAA we look at the value of someDog (42) and go to the Dog at 42 and change its name. On // BBB we change the value of someDog to 74. myDog (defined outside the method and still in scope) still has value 42. myDog is still active in the calling scope; you can access the Dog it points to (at 42 with name Fifi) outside foo(). You can no longer access that Dog inside foo() – Scott Stanchfield – 2016-06-17T17:22:21.607

    So it's exactly like in C, but because pointers are hard, they removed the pointer operators in order to "make it easier"! – dividebyzero – 2016-07-28T13:02:07.840

    1@dividebyzero Not to make it easier, to make it more secure (as in, for example, not possible to walk off the end of an array). Even good C/C++ programmers have that happen. – Scott Stanchfield – 2016-08-02T15:47:57.323

    2Good article. I do not like to talk about pointers together with Java though.. When one knows how Java and its variables scope/lifetime work, reference is the term to use. With pointers people start wondering about pointing pointers or given that a reference is a pointer, about dereferencing a reference in a C++ fashion. That's not good. A variable is made of bits -a value-, and this value can reference an Object. That is, it tells the JVM how to find an Object in the Heap. This value is copied/duplicated and passed to a method variable that then can find the same object. No need for pointers. – Gevorg – 2011-08-12T04:07:03.403

    @Özgür The key is BBB line, not AAA. If this was pass-by-reference, then BBB should changed myDog to "Fifi" then "Rowlf". It didn't because this was "pass-a-reference-by-value". – spicypumpkin – 2018-09-12T17:28:01.457

    So if the methood foo() returns someDog, and I use Dog rDog= foo(myDog), the rDog variable will be set to address 74 right? – rgamber – 2011-10-10T21:34:07.377

    1 437

    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 :)

    Eng.Fouad

    Posted 2008-09-02T20:14:29.270

    Reputation: 83 829

    59

    +1 Nice stuff. good diagrams. I also found a nice succinct page here http://www.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 – 2013-06-07T08:46:12.463

    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 – 2013-07-15T19:08:28.563

    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 – 2013-12-01T13:02:34.230

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

    @EvilWashingMachine no, why? You never see modifyReference letting "f" point to a completely different instance, do you? There's only one object in 6 and 7. Locally new references to tgat object can be created ("c" in the example) and the content of that one object can be changed (as happens in 7), but nothing within the method has the power to re-assign "f" to a second object. – Mike Braun – 2014-11-18T19:17:10.510

    @MikeBraun oh I see, I misunderstood when you said " BUT IT DID NOT CHANGE 'f'". I thought you also meant the object 'f' points to does not change. – Evil Washing Machine – 2014-11-20T14:18:52.567

    If I say that object in Java is passed to a method by copy of the reference, that would probably solve the whole discussion. Nice diagrams above would fit-in and support that statement. – MaxZoom – 2015-02-11T05:19:14.027

    The setAttribute method need to be accessed by Java reflection. http://tutorials.jenkov.com/java-reflection/private-fields-and-methods.html

    – herbertD – 2015-08-08T15:21:12.257

    By this definition, all languages are pass by value and pass by reference does not exist. Pass by reference means you can edit the caller's instance of what you received. Whether this is done through a pointer or using C++'s convenient syntax is irrelevant. – Cdaragorn – 2016-05-06T20:36:52.107

    4This 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 – 2016-05-21T12:38:43.853

    I am a little confused on line 5. I thought it goes from right to left; meaning object a is assigned object b and not the other way around. Or simply whatever the value of a is now whatever the value of b. Am I correct? – The_Martian – 2017-12-09T03:17:21.517

    673

    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!

    Gevorg

    Posted 2008-09-02T20:14:29.270

    Reputation: 8 528

    5Do 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 – 2012-02-25T03:29:07.113

    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 – 2012-02-25T21:25:22.503

    Okay I get it, passed-by-value and the value shared when passed! >:D No more p's and r's in Java! My problem now is, how can I change the value of an external variable from a method? Thanks again. – dpp – 2012-02-28T03:16:43.963

    when two objects refer to the same object, does that means it will occupy more memory in terms of an actual value? Or it will just occupy the memory for creating a pointer to the same place in memory? How does it work? – Ahmed – 2012-07-05T07:27:27.067

    @BratRosm you used the "p" word. But I will answer your question anyway... When two variable refer to the same object the object itself is not added to the memory again, just a tiny amount for the variable. Gevorg's image shows it best if you think of the shapes as memory usage. The big rectangular shape is the actual object stored in the heap the little circles are multiple references to it, they are really just a matter bits.

    – Geronimo – 2012-08-02T04:51:11.270

    one reason can be that java does not allow you to change that address so it gives you a copy of the reference(security) – curious – 2012-11-12T11:01:09.167

    nice +1 for In line #4 you can listen to the sound of silence, I would have added, or go have a coffee, but admitedly are very quick coffee! For those who really want to change the value of a member of an object, you need to use setters and getters, called from your object. If you want a default value available that is the same in all objects that you creat of that object type, you need a static member. If that needs to be modified you will need a static method to do so. This is why those responses above that 'modify' the member of an object must use a static method inside of the main class. – DaveM – 2013-06-07T09:09:02.620

    Then I suppose one could say that Java uses "pass-by-reference-copy" semantics. You're merely passing around a container whose contents are the memory address of an object on the heap. Therefore, if I call doSomething(someObject);, and inside said method I say someObject = new Object();, I'm merely changing the memory address inside of the someObject container; I'm not changing the caller's container's memory address at all. It's not strictly pass-by-value nor is it strictly pass-by-reference, but rather something that shares some properties of both. – Aquarelle – 2014-01-18T23:15:36.267

    One more thing: the semantics in Java bear a similarity, in a way, to copy-on-write (COW) semantics, in that you're passing a copy of an address to a method. At the moment the method is called, the caller's variable and method-local variable point to the same object and are thus considered to be "sharing" the same pointer value. However, the moment you assign a different object to the local, passed-in variable, the variable's memory reference changes, but the caller variable's reference does NOT change. That's COW. – Aquarelle – 2014-01-18T23:23:10.960

    8Sounds 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 – 2014-03-12T17:38:45.377

    3I 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 – 2014-08-20T17:42:17.033

    3So 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 – 2014-10-19T12:20:23.850

    I guess you've never heard of a NullPointerException. Java does indeed have pointers. But you probably won't take my word for it, so try this: "4.3.1 Objects An object is a class instance or an array. The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object." from the Java Language Spec 8, section 4.3.1. – Erick G. Hagstrom – 2015-08-30T16:54:27.033

    And all this conundrum from the simple shortcomings of our natural language. Java passes values, but this values happen to be references and since some will call a variable's name a reference too, one can surmise that what Java passes are actually those names. So if you're inclined to see it such, just keep in mind that some of those names in Java point to a reference to an object, so it's a reference to a reference (variable name (aka 'reference') => reference (aka 'true reference') => object on a heap). You're passing the second one, true reference, and not the first one. – z33k – 2018-02-25T11:58:06.073

    I have read numerous articles on this mess by Sun nomenclature, but this is the only one that is readable, entertaining and clearly understandable. Thank you ! – killjoy – 2018-05-02T13:19:12.113

    585

    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.

    SCdF

    Posted 2008-09-02T20:14:29.270

    Reputation: 25 548

    This article sums it up very well: http://academic.regis.edu/dbahr/GeneralPages/IntroToProgramming/JavaPassByValue.htm

    – eipark – 2013-04-16T16:33:33.923

    2@CarlosHeuberger, "primitives are immutable?". The point is that you can pretend that 'primitives' are actually (mutable) references to immutable objects. – Aaron McDaid – 2015-07-30T16:29:07.930

    4Pointers 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 – 2015-08-12T18:44:10.580

    7Since the values of the primitives are immutable (like String), the difference between the two cases is not really relevant. – Paŭlo Ebermann – 2011-02-03T01:23:04.473

    1This is another answer pointing out the largely semantic nature of the argument. The definition of reference provided in this answer would make Java "pass-by-reference." The author essentially admits as much in the last paragraph by stating that it is "indistinguishable in practice" from "pass-by-reference." I doubt OP is asking because of a desire to understand the Java implementation but rather to understand how to correctly use Java. If it were indistinguishable in practice, then there would be no point in caring and even thinking about it would be a waste of time. – Aaron – 2017-08-02T15:54:08.287

    1How is this answer correct? The very concept of "pass-by-value", just like "value types", implies your are dealing with data that lives directly in variables and is thus copied on assignment. Just because Java doesn't provide access to raw pointers doesn't matter: Objects act fundamentally different to primitive data types. They are not both pass-by-value – RecursiveExceptionException – 2017-10-16T23:56:51.323

    4Exactly. 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 – 2011-07-31T04:50:55.707

    not if primitive were passed by reference then a method call that modify its parameter would impact the caller. This isn't the case. – Nicolas Bousquet – 2018-02-02T17:37:37.673

    5primitives are immutable? is that new in Java 7? – Carlos Heuberger – 2011-08-22T11:26:09.647

    What's the meaning reference in your context ? Is it a stack pointer? – shaoyihe – 2018-06-20T07:22:37.503

    I think the correct way to say it is that java is pass by reference if it is objects, because you are passing the reference value of the object. and if it is primitive type it is pass by value. this is what Einstein said... make things simple but not simplier :D! peace everyone! – Artanis Zeratul – 2018-11-01T22:38:11.650

    288

    Java passes references by value.

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

    ScArcher2

    Posted 2008-09-02T20:14:29.270

    Reputation: 60 192

    16Keep 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 – 2012-01-26T22:17:56.820

    Java passes references by value. You can change data at the memory the reference points to. In the method you can change the reference variable, but after the function exits the reference is reverted back (but not the memory this reference is pointing at). – Willmore – 2013-11-08T11:03:21.627

    5Sounds 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 – 2014-03-12T17:38:26.753

    2Java 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 – 2014-11-19T16:38:17.390

    @theferrit32 This is straight up ridiculous. Obviously, at the lowest possible level, there will be values because without values there's nothing there. It's utterly stupid because you are presenting a fact not for whether Java is purely pass-by-value but rather for why the destinction between pass-by-value and pass-by-reference are meaningless. Again, without data there's no data, so obviously every pass-by-reference implementation will deal with data at some level. But abstracting the concept to such a degree is ridiculous. Why not call Java "transfer-by-entity" – RecursiveExceptionException – 2017-10-17T00:05:07.087

    There is a difference though, because some languages do pass by reference, which is a different data type from a basic pointer, which is essentially what Java is using. Consider a reference to be just an abstraction level above a pointer. If you have a reference you can modify the value of the actual memory location used by the function caller. Java does not work this way though, it passes a new memory location containing the value of the object pointer, not a reference to the pointer. In Java you cannot modify the value passed from the caller into the function, in some languages you can. – theferrit32 – 2017-10-17T01:41:42.520

    25But 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 – 2011-07-24T19:13:09.897

    31I 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 – 2011-08-01T14:19:38.150

    I wasn't disagreeing with you. Sorry if that wasn't clear! – Timmmm – 2011-08-02T09:54:28.670

    The difference is between a reference and the reference of a reference. If you only have a reference you can modify at will what it refer to, but not the reference itself. For that you need a reference of the reference. This is exactly what you get in C++ when a parameter is passed by reference. You don't copy the parameter value, but a reference to it. If the parameter is itself a reference, your get a reference of a reference. – Nicolas Bousquet – 2018-02-02T17:43:20.497

    207

    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".

    cutmancometh

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 018

    6However, 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 – 2013-11-01T06:53:33.857

    30People 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 – 2013-12-18T04:48:00.880

    2That's not correct @cHao. Java does not place any live objects on the stack. It may be an "implementation detail" in that it's not specifically outline in the Java spec, but that fact is that all Java implementations place all objects in the heap. – cutmancometh – 2013-12-18T09:19:14.997

    2

    Actually, I lied: it is in the spec. The stack is for locals and partial results link, and the heap is for objects link

    – cutmancometh – 2013-12-18T09:22:57.630

    8It'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 – 2013-12-18T14:38:19.103

    9And 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 – 2013-12-18T14:55:10.867

    9Agree 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 – 2014-03-02T15:37:40.123

    2It has nothing to do with stack vs heap allocation. It has to do with indirection. Stack locations have addresses. At any rate, Java passes all arguments by value. – Aluan Haddad – 2016-04-24T14:13:06.953

    1This answer is just wrong. Both references and primitives can be found on either the stack or the heap. And which it is is entirely irrelevant to the whole "pass by reference" vs "pass by value" issue. Your references and your primitives get passed by value, regardless of whether they live on the heap or the stack. – Dawood ibn Kareem – 2017-01-25T10:05:10.497

    Right, so I have 3 concerns with your critique: 1) Objects can't be found on the stack. A reference to an object can be found on the stack, which is exactly what I showed in my diagrams. But the object itself exists on the heap. 2) So, yes, primitives can be found on the heap, but if and only if they are properties of an object. Also, shown in my diagrams. Local primitives are on the stack. 3) Saying "references... get passed by value" is the very definition of passing by reference. "Passing a reference by it's value" is simply passing the thing it references by reference. – cutmancometh – 2017-01-25T18:14:16.820

    Also, I'm not saying Java is pass-by-reference. I've been saying from the beginning that "pass-by-reference vs. pass-by-value" is a stupid argument because it doesn't yield any useful understanding, so here's a model of what's happening intended to help you understand why local primitives behave one way and objects behave another way, when passed into a method. Simply saying "Java is pass by reference" is incomplete because it often requires additional explanation. I was attempting to provide some additional information, rather than just a short sound-byte. – cutmancometh – 2017-01-25T18:31:46.070

    @cutmancometh I have understood your answer very well. But I am confused that if this answer is true, then why a simple swap fails? I am talking about a swap method that takes two arguments and then inside the method you create a temp object and then do the swapping. If possible for you, can you explain that scenario in your answer? Please – Faraz Durrani – 2017-03-25T20:37:09.893

    if not in this answer then somewhere. Please explain to me why swap method fails! – Faraz Durrani – 2017-03-25T20:38:02.543

    Sure, can you be more specific? Could post post the code you're referring to in ideone.com, or even just pastebin.com? There's plenty of room for abiguity in the term "swap method", and I'd hate to give you incomplete information. – cutmancometh – 2017-04-03T13:37:38.187

    @cutmancometh if it is a stupid argument, how can we describe the distinction? It exists in other languages. It is significant to Java in that other languages share a largely common call syntax. Consider C#'s ref. – Aluan Haddad – 2017-04-29T03:33:00.077

    169

    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.

    Eclipse

    Posted 2008-09-02T20:14:29.270

    Reputation: 38 230

    7+1 I would also add Dog **objPtrPtr to the C++ example, that way we can modify what the pointer "points to". – Amro – 2014-07-02T03:59:12.063

    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 – 2017-08-02T15:32:06.897

    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 – 2018-11-06T09:11:44.563

    147

    Java passes references to objects by value.

    John Channing

    Posted 2008-09-02T20:14:29.270

    Reputation: 4 267

    As simple as that ! – Ivan Kaloyanov – 2018-05-30T10:39:08.633

    142

    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.

    Hank Gay

    Posted 2008-09-02T20:14:29.270

    Reputation: 51 460

    7I would rather say that bar is a copy of the reference baz (or baz alias), that points initially to the same object. – MaxZoom – 2015-02-11T05:36:27.197

    140

    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".

    Jörg W Mittag

    Posted 2008-09-02T20:14:29.270

    Reputation: 286 660

    2I 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 – 2010-09-08T14:16:37.987

    2I 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 – 2010-10-25T20:03:18.943

    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 – 2016-01-08T00:14:02.917

    7Call by Sharing – wulfgarpro – 2011-09-16T00:29:43.143

    99

    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.

    JacquesB

    Posted 2008-09-02T20:14:29.270

    Reputation: 34 280

    7@Gevorg - Then what is a "NullPointerException"? – Hot Licks – 2013-09-22T14:09:21.067

    4@Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException. – JacquesB – 2013-09-23T14:08:10.023

    4It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding. – Hot Licks – 2013-09-23T15:46:14.263

    10Colloquially called a pointer. – Prof. Falken – 2011-02-09T09:50:58.183

    I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity. – moronkreacionz – 2015-12-29T21:36:08.967

    75

    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
    

    Srle

    Posted 2008-09-02T20:14:29.270

    Reputation: 5 873

    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 – 2015-10-22T06:42:28.543

    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 – 2016-12-20T01:29:33.180

    66

    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.

    Ganesh

    Posted 2008-09-02T20:14:29.270

    Reputation: 826

    64

    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.

    karatedog

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 742

    1In 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 – 2014-01-10T17:02:04.357

    ...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 – 2014-01-10T17:04:46.480

    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 – 2014-01-10T22:48:25.603

    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 – 2014-01-10T22:52:31.693

    ...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 – 2014-01-10T22:54:39.737

    50

    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.

    George Paolo Flores

    Posted 2008-09-02T20:14:29.270

    Reputation: 454

    50

    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.

    kukudas

    Posted 2008-09-02T20:14:29.270

    Reputation: 2 910

    +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 – 2013-12-17T21:24:26.507

    "..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 – 2016-11-24T13:16:43.373

    46

    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]
    

    spiderman

    Posted 2008-09-02T20:14:29.270

    Reputation: 5 388

    45

    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:\desktop\abc-shortcut so when you access the file from C:\desktop\abc.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:\desktop\abc.txt ) address and 234jdid(copied address like C:\desktop\abc-shortcut which actually contains the original address of the file inside) .. So for better understanding make shortcut file and feel...

    Himanshu arora

    Posted 2008-09-02T20:14:29.270

    Reputation: 151

    44

    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.

    Jared Oberhaus

    Posted 2008-09-02T20:14:29.270

    Reputation: 12 103

    43

    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).

    Sotirios Delimanolis

    Posted 2008-09-02T20:14:29.270

    Reputation: 205 496

    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 – 2017-08-02T15:39:05.147

    34

    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.

    shsteimer

    Posted 2008-09-02T20:14:29.270

    Reputation: 16 014

    2I 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 – 2017-01-25T10:09:26.797

    31

    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();
    }
    

    Gaurav

    Posted 2008-09-02T20:14:29.270

    Reputation: 161

    4This 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 – 2017-06-10T23:24:59.727

    31

    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.

    pek

    Posted 2008-09-02T20:14:29.270

    Reputation: 9 229

    i understood with this answer – Kumaresan Perumal – 2018-04-25T18:04:21.073

    30

    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.

    user1767316

    Posted 2008-09-02T20:14:29.270

    Reputation: 880

    29

    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.

    SWD

    Posted 2008-09-02T20:14:29.270

    Reputation: 254

    3"pass by copy" is what pass-by-value means. – T.J. Crowder – 2016-08-07T08:46:02.163

    24

    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)

    sven

    Posted 2008-09-02T20:14:29.270

    Reputation: 11 110

    23

    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?

    Rusty Shackleford

    Posted 2008-09-02T20:14:29.270

    Reputation: 39

    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 – 2010-09-07T22:02:17.373

    1Yeah, 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 – 2011-02-03T01:27:19.620

    23

    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++.

    Paul de Vrieze

    Posted 2008-09-02T20:14:29.270

    Reputation: 4 549

    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 – 2015-02-11T05:58:48.940

    21

    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!

    Christian

    Posted 2008-09-02T20:14:29.270

    Reputation: 4 466

    I think you nailed it by saying you can't change the reference from the object itself – sakhunzai – 2017-03-30T05:41:44.133

    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 – 2017-03-30T06:00:56.770

    20

    Throughout all the answers we see that Java pass-by-value or rather as @Gevorg wrote: "pass-by-copy-of-the-variable-value" and this is the idea that we should have in mind all the time.

    I am focusing on examples that helped me understand the idea and it is rather addendum to previous answers.

    From [1] In Java you always are passing arguments by copy; that is you're always creating a new instance of the value inside the function. But there are certain behaviors that can make you think you're passing by reference.

    • Passing by copy: When a variable is passed to a method/function, a copy is made (sometimes we hear that when you pass primitives, you're making copies).

    • Passing by reference: When a variable is passed to a method/function, the code in the method/function operates on the original variable (You're still passing by copy, but references to values inside the complex object are parts of both versions of the variable, both the original and the version inside the function. The complex objects themselves are being copied, but the internal references are being retained)

    Examples of Passing by copy/ by value

    Example from [ref 1]

    void incrementValue(int inFunction){
      inFunction ++;
      System.out.println("In function: " + inFunction);
    }
    
    int original = 10;
    System.out.print("Original before: " + original);
    incrementValue(original);
    System.out.println("Original after: " + original);
    
    We see in the console:
     > Original before: 10
     > In Function: 11
     > Original after: 10 (NO CHANGE)
    

    Example from [ref 2]

    shows nicely the mechanism watch max 5 min

    (Passing by reference) pass-by-copy-of-the-variable-value

    Example from [ref 1] (remember that an array is an object)

    void incrementValu(int[] inFuncion){
      inFunction[0]++;
      System.out.println("In Function: " + inFunction[0]);
    }
    
    int[] arOriginal = {10, 20, 30};
    System.out.println("Original before: " + arOriginal[0]);
    incrementValue(arOriginal[]);
    System.out.println("Original before: " + arOriginal[0]);
    
    We see in the console:
      >Original before: 10
      >In Function: 11
      >Original before: 11 (CHANGE)
    

    The complex objects themselves are being copied, but the internal references are being retained.

    Example from[ref 3]

    package com.pritesh.programs;
    
    class Rectangle {
      int length;
      int width;
    
      Rectangle(int l, int b) {
        length = l;
        width = b;
      }
    
      void area(Rectangle r1) {
        int areaOfRectangle = r1.length * r1.width;
        System.out.println("Area of Rectangle : " 
                                + areaOfRectangle);
      }
    }
    
    class RectangleDemo {
      public static void main(String args[]) {
        Rectangle r1 = new Rectangle(10, 20);
        r1.area(r1);
      }
    }
    

    The area of the rectangle is 200 and the length=10 and width=20

    Last thing I would like to share was this moment of the lecture: Memory Allocation which I found very helpful in understanding the Java passing by value or rather “pass-by-copy-of-the-variable-value” as @Gevorg has written.

    1. REF 1 Lynda.com
    2. REF 2 Professor Mehran Sahami
    3. REF 3 c4learn

    Michał Żbikowski

    Posted 2008-09-02T20:14:29.270

    Reputation: 39

    Java by default is said to be pass by reference. usually when a mutable object is passed to some methods then any changes done with that object reference will be reflected to the other parts too using same object reference. But in case of immutable object, if reference is reassigned to some other objects, then it will not be reflected to the other parts, entirely new objects will be created. – Shailendra Singh – 2016-07-08T15:26:49.373

    1@ShailendraSingh Java never passes by reference, period. See Gaurav's answer for a clear proof of this. – David Schwartz – 2017-06-10T23:27:00.057

    "pass-by-copy-of-the-variable-value" is slightly misleading. An actual argument is a value, which is the result of evaluating an expression. There need be no variable in the expression. – Tom Blodget – 2017-10-23T23:04:38.923

    18

    It's really quite, quite simple:

    For a variable of primitive type (eg. int, boolean, char, etc...), when you use its name for a method argument, you are passing the value contained in it (5, true, or 'c'). This value gets "copied", and the variable retains its value even after the method invocation.

    For a variable of reference type (eg. String, Object, etc...), when you use its name for a method argument, you are passing the value contained in it (the reference value that "points" to the object). This reference value gets "copied", and the variable retains its value even after the method invocation. The reference variable keeps "pointing" to the same object.

    Either way, you're always passing stuff by value.


    Compare this to say C++ where you can have a method to take an int&, or in C# where you could have take a ref int (although, in this case, you also have to use the ref modifier when passing the variable's name to the method.)

    Fernando Espinosa

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 901

    Also remembering that StringS are immutable in Java. – wulfgarpro – 2012-09-01T07:58:53.477

    I find it helpful to think of class-type variables as holding "object IDs". Java's default string representation of objects works well with such a description. If one sets Foo to "Car #1234", and copies Foo to Bar, then both Foo and Bar will hold "Car #1234". Saying Foo.SetColor(Colors.Blue) will paint "Car #1234" blue. The other description I use for such storage locations is "promiscuous object references", since code which passes such a reference to an object has no way of controlling how the recipient might share it. – supercat – 2013-05-25T04:12:43.160

    Variables don't enter into the way Java works. Actual arguments are from evaluating expressions. – Tom Blodget – 2018-07-16T00:22:58.697

    18

    Java copies the reference by value. So if you change it to something else (e.g, using new) the reference does not change outside the method. For native types, it is always pass by value.

    fastcodejava

    Posted 2008-09-02T20:14:29.270

    Reputation: 23 480

    17

    Java is pass by constant reference where a copy of the reference is passed which means that it is basically a pass by value. You might change the contents of the reference if the class is mutable but you cannot change the reference itself. In other words the address can not be changed since it is passed by value but the content that is pointed by the address can be changed. In case of immutable classes, the content of the reference cannot be changed either.

    fatma.ekici

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 426

    1There is no such thing as a 'constant referenece' in Java unless the programmer specifies 'finally'. – user207421 – 2013-08-02T10:05:23.940

    What I meant by constant reference is, there is no way to change the reference itself by saying new MyClass() in a function. If I put it correctly, there object references are passed by value which means a copy of the reference is passed so you can change the data where that reference refers to but you can not change it with new operator and allocate a new object. – fatma.ekici – 2013-09-09T13:06:23.007

    So fix your answer. If it was a constant you couldn't reassign it inside the called method, and you can, unless you specify final. – user207421 – 2014-09-25T00:41:47.970

    16

    Java always uses call by value. That means the method gets copy of all parameter values.

    Consider next 3 situations:

    1) Trying to change primitive variable

    public static void increment(int x) { x++; }
    
    int a = 3;
    increment(a);
    

    x will copy value of a and will increment x, a remains the same

    2) Trying to change primitive field of an object

    public static void increment(Person p) { p.age++; }
    
    Person pers = new Person(20); // age = 20
    increment(pers);
    

    p will copy reference value of pers and will increment age field, variables are referencing to the same object so age is changed

    3) Trying to change reference value of reference variables

    public static void swap(Person p1, Person p2) {
        Person temp = p1;
        p1 = p2;
        p2 = temp;
    }
    
    Person pers1 = new Person(10);
    Person pers2 = new Person(20);
    swap(pers1, pers2);
    

    after calling swap p1, p2 copy reference values from pers1 and pers2, are swapping with values, so pers1 and pers2 remain the same

    So. you can change only fields of objects in method passing copy of reference value to this object.

    Placinta Alexandru

    Posted 2008-09-02T20:14:29.270

    Reputation: 34

    16

    Java, for sure, without a doubt, is "pass by value". Also, since Java is (mostly) object-oriented and objects work with references, it's easy to get confused and think of it to be "pass by reference"

    Pass by value means you pass the value to the method and if the method changes the passed value, the real entity doesn't change. Pass by reference, on the other hand, means a reference is passed to the method, and if the method changes it, the passed object also changes.

    In Java, usually when we pass an object to a method, we basically pass the reference of the object as-a-value because that's how Java works; it works with references and addresses as far as Object in the heap goes.

    But to test if it is really pass by value or pass by reference, you can use a primitive type and references:

    @Test
    public void sampleTest(){
        int i = 5;
        incrementBy100(i);
        System.out.println("passed ==> "+ i);
        Integer j = new Integer(5);
        incrementBy100(j);
        System.out.println("passed ==> "+ j);
    }
    /**
     * @param i
     */
    private void incrementBy100(int i) {
        i += 100;
        System.out.println("incremented = "+ i);
    }
    

    The output is:

    incremented = 105
    passed ==> 5
    incremented = 105
    passed ==> 5
    

    So in both cases, whatever happens inside the method doesn't change the real Object, because the value of that object was passed, and not a reference to the object itself.

    But when you pass a custom object to a method, and the method and changes it, it will change the real object too, because even when you passed the object, you passed it's reference as a value to the method. Let's try another example:

    @Test
    public void sampleTest2(){
        Person person = new Person(24, "John");
        System.out.println(person);
        alterPerson(person);
        System.out.println(person);
    }
    
    /**
     * @param person
     */
    private void alterPerson(Person person) {
        person.setAge(45);
        Person altered = person;
        altered.setName("Tom");
    }
    
    private static class Person{
        private int age;
        private String name; 
    
        public Person(int age, String name) {
            this.age=age;
            this.name =name;
        }
    
        public int getAge() {
            return age;
        }
    
        public void setAge(int age) {
            this.age = age;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        @Override
        public String toString() {
            StringBuilder builder = new StringBuilder();
            builder.append("Person [age=");
            builder.append(age);
            builder.append(", name=");
            builder.append(name);
            builder.append("]");
            return builder.toString();
        }
    
    }
    

    In this case, the output is:

    Person [age=24, name=John]
    Person [age=45, name=Tom]
    

    Rahul Kumar

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 605

    15

    So many long answers. Let me give a simple one:

    • Java always passes everything by value
    • that means also references are passed by value

    In short, you can not modify value of any parameter passed, but you can call methods or change attributes of an object reference passed.

    Gee Bee

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 610

    15

    One of the biggest confusion in Java programming language is whether Java is Pass by Value or Pass by Reference.

    First of all, we should understand what is meant by pass by value or pass by reference.

    Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that’s why it’s called pass by value.

    Pass by Reference: An alias or reference to the actual parameter is passed to the method, that’s why it’s called pass by reference.

    Let’s say we have a class Balloon like below.

    public class Balloon {
    
        private String color;
    
        public Balloon(){}
    
        public Balloon(String c){
            this.color=c;
        }
    
        public String getColor() {
            return color;
        }
    
        public void setColor(String color) {
            this.color = color;
        }
    }
    

    And we have a simple program with a generic method to swap two objects, the class looks like below.

    public class Test {
    
        public static void main(String[] args) {
    
            Balloon red = new Balloon("Red"); //memory reference 50
            Balloon blue = new Balloon("Blue"); //memory reference 100
    
            swap(red, blue);
            System.out.println("red color="+red.getColor());
            System.out.println("blue color="+blue.getColor());
    
            foo(blue);
            System.out.println("blue color="+blue.getColor());
    
        }
    
        private static void foo(Balloon balloon) { //baloon=100
            balloon.setColor("Red"); //baloon=100
            balloon = new Balloon("Green"); //baloon=200
            balloon.setColor("Blue"); //baloon = 200
        }
    
        //Generic swap method
        public static void swap(Object o1, Object o2){
            Object temp = o1;
            o1=o2;
            o2=temp;
        }
    }
    

    When we execute the above program, we get following output.

    red color=Red
    blue color=Blue
    blue color=Red
    

    If you look at the first two lines of the output, it’s clear that swap method didn’t work. This is because Java is passed by value, this swap() method test can be used with any programming language to check whether it’s pass by value or pass by reference.

    Let’s analyze the program execution step by step.

    Balloon red = new Balloon("Red");
    Balloon blue = new Balloon("Blue");
    

    When we use the new operator to create an instance of a class, the instance is created and the variable contains the reference location of the memory where the object is saved. For our example, let’s assume that “red” is pointing to 50 and “blue” is pointing to 100 and these are the memory location of both Balloon objects.

    Now when we are calling swap() method, two new variables o1 and o2 are created pointing to 50 and 100 respectively.

    So below code snippet explains what happened in the swap() method execution.

    public static void swap(Object o1, Object o2){ //o1=50, o2=100
        Object temp = o1; //temp=50, o1=50, o2=100
        o1=o2; //temp=50, o1=100, o2=100
        o2=temp; //temp=50, o1=100, o2=50
    } //method terminated
    

    Notice that we are changing values of o1 and o2 but they are copies of “red” and “blue” reference locations, so actually, there is no change in the values of “red” and “blue” and hence the output.

    If you have understood this far, you can easily understand the cause of confusion. Since the variables are just the reference to the objects, we get confused that we are passing the reference so Java is passed by reference. However, we are passing a copy of the reference and hence it’s pass by value. I hope it clears all the doubts now.

    Now let’s analyze foo() method execution.

    private static void foo(Balloon balloon) { //baloon=100
        balloon.setColor("Red"); //baloon=100
        balloon = new Balloon("Green"); //baloon=200
        balloon.setColor("Blue"); //baloon = 200
    }
    

    The first line is the important one when we call a method the method is called on the Object at the reference location. At this point, the balloon is pointing to 100 and hence it’s color is changed to Red.

    In the next line, balloon reference is changed to 200 and any further methods executed are happening on the object at memory location 200 and not having any effect on the object at memory location 100. This explains the third line of our program output printing blue color=Red.

    I hope above explanation clear all the doubts, just remember that variables are references or pointers and its copy is passed to the methods, so Java is always passed by value. It would be more clear when you will learn about Heap and Stack memory and where different objects and references are stored.

    Raj S. Rusia

    Posted 2008-09-02T20:14:29.270

    Reputation: 427

    13

    Unlike some other languages, Java does not allow you to choose pass-by-value or pass by-reference—all arguments are passed by value. A method call can pass two types of values to a method—copies of primitive values (e.g., values of int and double) and copies of references to objects.

    When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.

    When it comes to objects, objects themselves cannot be passed to methods. So we pass address of the object which is held in reference variable.

    How Java creates and stores objects. When we create an object we store the object’s adress in a reference variable. “Scanner input” is the type and reference variable, “=” is the assignment operator, “new” asks for required amount of space from the system. The constructor to the right of keyword new which creates the object is called implicitly by the keyword new. Address of the created object(result of right variable, which is an expression) is assigned to the left variable (which is a reference variable with a name and a type specified) using the assign operator. “new Account()” is called “class instance creation expression”.

    Although an object’s reference is passed by value, a method can still interact with the referenced object by calling its public methods using the copy of the object’s reference. Since the reference stored in the parameter is a copy of the reference that was passed as an argument, the parameter in the called method and the argument in the calling method refer to the same object in memory.

    Passing references to arrays, instead of the array objects themselves, makes sense for performance reasons. Because everything in Java is passed by value, if array objects were passed, a copy of each element would be passed. For large arrays, this would waste time and consume considerable storage for the copies of the elements.

    In the image below you can see we have two reference variables(These are called pointers in C/C++. And i think that term makes it easier to understand this feature.) in the main method. Primitive and reference variables are kept in stack memory(left side in images below). These reference variables "point" (as C/C++ programmers call it) or reference to a and b arrays which are objects(values these reference variables hold are addresses of objects) in heap memory(right side in images below).

    Pass by value example 1

    If we pass the value of array1 reference variable as an argument to the reverseArray method, a reference variable is created in the method and that reference variable starts pointing to the same array(a).

    reverseArray(array1);
    

    ...

    public void reverseArray(Int[] array1)
    {
       ...
    }
    

    Pass by value example 2

    So, if we say

    array1[0] = 5;
    

    in reverseArray method, it will make a change in array a.

    We have another reference variable in reverseArray method(array2) that points to an array c. If we were to say

    array1 = array2;
    

    in reverseArray method, then the reference variable array1 in method reverseArray would stop pointing to array a and start pointing to array c (Dotted line in second image).

    If we return value of reference variable array2 as the return value of method reverseArray and assign this value to reference variable array1 in main method, array1 in main will start pointing to array c.

    enter image description here

    You can assign value of array2 in main to array1 too. array1 would start pointing to b.

    madcobra

    Posted 2008-09-02T20:14:29.270

    Reputation: 68

    12

    Have a look at this code. This code will not throw NullPointerException... It will print "Vinay"

    public class Main {
        public static void main(String[] args) {
            String temp = "Vinay";
            print(temp);
            System.err.println(temp);
        }
    
        private static void print(String temp) {
            temp = null;
        }
    }
    

    If Java is pass by reference then it should have thrown NullPointerException as reference is set to Null.

    Vinay Lodha

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 883

    6Doesn't answer the question. The OP is asking for an explanation, not just a proof. – user207421 – 2013-08-02T10:04:53.093

    The static is throwing it off.

    public class Main { public static void main(String[] args) { Main m = new Main(); m.aaa(); }

    public void aaa()
     {
      String temp = "Vinay";
          print(temp);
          System.err.println(temp);
     }
    
    private void print(String temp) {
        temp = null;
    }
    

    }

    the above code does not NPE. – Milhous – 2010-08-12T21:27:49.183

    Didn't got what you are trying to say..? – Vinay Lodha – 2010-08-13T06:27:20.687

    12

    The major cornerstone knowledge must be the quoted one,

    When an object reference is passed to a method, the reference itself is passed by use of call-by-value. However, since the value being passed refers to an object, the copy of that value will still refer to the same object referred to by its corresponding argument.

    Java: A Beginner's Guide, Sixth Edition, Herbert Schildt

    snr

    Posted 2008-09-02T20:14:29.270

    Reputation: 5 117

    12

    Java is strictly passed by value

    When I say pass by value it means whenever caller has invoked the callee the arguments(ie: the data to be passed to the other function) is copied and placed in the formal parameters (callee's local variables for receiving the input). Java makes data communications from one function to other function only in a pass by value environment.

    An important point would be to know that even C language is strictly passed by value only:
    ie: Data is copied from caller to the callee and more ever the operation performed by the callee are on the same memory location and what we pass them is the address of that location that we obtain from (&) operator and the identifier used in the formal parameters are declared to be a pointer variable (*) using which we can get inside the memory location for accessing the data in it.

    Hence here the formal parameter is nothing but mere aliases for that location. And any modifications done on that location is visible where ever that scope of the variable (that identifies that location) is alive.

    In Java, there is no concept of pointers (ie: there is nothing called a pointer variable), although we can think of reference variable as a pointer technically in java we call it as a handle. The reason why we call the pointer to an address as a handle in java is because a pointer variable is capable of performing not just single dereferencing but multiple dereferencing for example: int *p; in P means p points to an integer and int **p; in C means p is pointer to a pointer to an integer we dont have this facility in Java, so its absolutely correct and technically legitimate to say it as an handle, also there are rules for pointer arithmetic in C. Which allows performing arithmetic operation on pointers with constraints on it.

    In C we call such mechanism of passing address and receiving them with pointer variables as pass by reference since we are passing their addresses and receiving them as pointer variable in formal parameter but at the compiler level that address is copied into pointer variable (since data here is address even then its data ) hence we can be 100% sure that C is Strictly passed by value (as we are passing data only)

    (and if we pass the data directly in C we call that as pass by value.)

    In java when we do the same we do it with the handles; since they are not called pointer variables like in (as discussed above) even though we are passing the references we cannot say its pass by reference since we are not collecting that with a pointer variable in Java.

    Hence Java strictly use pass by value mechanism

    NAGHMAAN MOHASEEN

    Posted 2008-09-02T20:14:29.270

    Reputation: 19

    12

    This is the best way to answer the question imo...

    First, we must understand that, in Java, the parameter passing behavior...

    public void foo(Object param)
    {
      // some code in foo...
    }
    
    public void bar()
    {
      Object obj = new Object();
    
      foo(obj);
    }
    

    is exactly the same as...

    public void bar()
    {
      Object obj = new Object();
    
      Object param = obj;
    
      // some code in foo...
    }
    

    not considering stack locations, which aren't relevant in this discussion.

    So, in fact, what we're looking for in Java is how variable assigment works, which could be classified, imo, as mutable or immutable assignment (pass-by-reference or pass-by-value, respectivelly), when an assignment does change or does not change a previous assignment.

    Having this in mind, we can run some Java code to find the answer by ourselves.

    public class Program
    {
      public static class MyInteger
      {
        public int value;
    
        public MyInteger(int number)
        {
          this.value = number;
        }
      }
    
      public static void main(String[] args)
      {
        MyInteger obj1, obj2, obj3;
    
        System.out.println("[1] Create some new MyInteger objects...");
    
        obj1 = new MyInteger(9);
        System.out.println("obj1 = new  -> obj1 value: " + obj1.value);
    
        obj2 = new MyInteger(8);
        System.out.println("obj2 = new  -> obj2 value: " + obj2.value);
    
        obj3 = new MyInteger(7);
        System.out.println("obj3 = new  -> obj3 value: " + obj3.value);
    
        System.out.println("");
    
        System.out.println("[2] Now lets assign some of them to another object...");
    
        obj3 = obj2;
        System.out.println("obj3 = obj2 -> obj3 value: " + obj3.value);
    
        obj2 = obj1;
        System.out.println("obj2 = obj1 -> obj2 value: " + obj2.value);
    
        System.out.println("");
    
        System.out.println("[3] So, if obj3 = obj2 and obj2 = obj1, what is the value of obj3?");
    
        System.out.println("obj3        -> obj3 value: " + obj3.value);
    
        System.out.println("");
    
        System.out.println("[4] Lets assign to obj1 value the number 1...");
    
        obj1.value = 1;
        System.out.println("obj1        -> obj1 value: " + obj1.value);
    
        System.out.println("");
    
        System.out.println("[5] So, if obj2 = obj1, what is the value of obj2?");
    
        System.out.println("obj2        -> obj2 value: " + obj2.value);
    
        System.out.println("");
    
        System.out.println("[6] end.");
      }
    }
    

    This is the output of my run:

    [1] Create some new MyInteger objects...
    obj1 = new  -> obj1 value: 9
    obj2 = new  -> obj2 value: 8
    obj3 = new  -> obj3 value: 7
    
    [2] Now lets assign some of them to another object...
    obj3 = obj2 -> obj3 value: 8
    obj2 = obj1 -> obj2 value: 9
    
    [3] So, if obj3 = obj2 and obj2 = obj1, what is the value of obj3?
    obj3        -> obj3 value: 8
    
    [4] Lets assign to obj1 value the number 1...
    obj1        -> obj1 value: 1
    
    [5] So, if obj2 = obj1, what is the value of obj2?
    obj2        -> obj2 value: 1
    
    [6] end.
    

    You can see in [3] that assigning to obj2 the variable obj1 doesn't change the previous assignment of obj2 to obj3, so they were immutable assignments (pass-by-value) or copy of variables. But the assignment of a new value to obj1 in [4] just changed the value of obj2 in [5], which looks like a mutable assignment (pass-by-reference), not like a copy. So how could this happen? I think it's the confusing point to most people, but still Java did the variable copy. The point is... in Java, the content of a primitive type variable is different from the content of a complex type variable.

    A single instance of a complex type can allocate a good amount of the available memory, so Java would end up all the memory really fast doing content copies through variable assignment... and it would keep the CPU much more busy too. To avoid this, a complex type variable doesn't hold the object instance itself... it holds the memory address where the instance is stored, as the cost of doing address copy is much lower. So, after [2], obj1 and obj2 are two distinct copies of the same memory address that holds the object instance. Thus, updating the object in this address through one variable will change the result you'll get on the other variable just like in [4] and [5], but still these variables are distinct copies through what I call immutable assignment.

    Hope it's clear now.

    Felypp Oliveira

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 676

    11

    A simple test to check whether a language supports pass-by-reference is simply writing a traditional swap. Can you write a traditional swap(a,b) method/function in Java?

    A traditional swap method or function takes two arguments and swaps them such that variables passed into the function are changed outside the function. Its basic structure looks like

    (Non-Java) Basic swap function structure

    swap(Type arg1, Type arg2) {
        Type temp = arg1;
        arg1 = arg2;
        arg2 = temp;
    }
    

    If you can write such a method/function in your language such that calling

    Type var1 = ...;
    Type var2 = ...;
    swap(var1,var2);
    

    actually switches the values of the variables var1 and var2, the language supports pass-by-reference. But Java does not allow such a thing as it supports passing the values only and not pointers or references.

    khakishoiab

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 667

    9

    Java passes primitive types by value and class types by reference

    Now, people like to bicker endlessly about whether "pass by reference" is the correct way to describe what Java et al. actually do. The point is this:

    1. Passing an object does not copy the object.
    2. An object passed to a function can have its members modified by the function.
    3. A primitive value passed to a function cannot be modified by the function. A copy is made.

    In my book that's called passing by reference.

    Brian Bi - Which programming languages are pass by reference?

    georgeawg

    Posted 2008-09-02T20:14:29.270

    Reputation: 32 128

    8

    In an attempt to add even more to this, I thought I'd include the SCJP Study Guide section on the topic. This is from the guide that is made to pass the Sun/Oracle test on the behaviour of Java so it's a good source to use for this discussion.

    Passing Variables into Methods (Objective 7.3)

    7.3 Determine the effect upon object references and primitive values when they are passed into methods that perform assignments or other modifying operations on the parameters.

    Methods can be declared to take primitives and/or object references. You need to know how (or if) the caller's variable can be affected by the called method. The difference between object reference and primitive variables, when passed into methods, is huge and important. To understand this section, you'll need to be comfortable with the assignments section covered in the first part of this chapter.

    Passing Object Reference Variables

    When you pass an object variable into a method, you must keep in mind that you're passing the object reference, and not the actual object itself. Remember that a reference variable holds bits that represent (to the underlying VM) a way to get to a specific object in memory (on the heap). More importantly, you must remember that you aren't even passing the actual reference variable, but rather a copy of the reference variable. A copy of a variable means you get a copy of the bits in that variable, so when you pass a reference variable, you're passing a copy of the bits representing how to get to a specific object. In other words, both the caller and the called method will now have identical copies of the reference, and thus both will refer to the same exact (not a copy) object on the heap.

    For this example, we'll use the Dimension class from the java.awt package:

    1. import java.awt.Dimension;
    2. class ReferenceTest {
    3.     public static void main (String [] args) {
    4.         Dimension d = new Dimension(5,10);
    5.         ReferenceTest rt = new ReferenceTest();
    6.         System.out.println("Before modify() d.height = " + d.height);
    7.         rt.modify(d);
    8.         System.out.println("After modify() d.height = "
    9.     }
    10.
    11.
    12.
    13.   }
    14. }
    

    When we run this class, we can see that the modify() method was indeed able to modify the original (and only) Dimension object created on line 4.

    C:\Java Projects\Reference>java ReferenceTest
    Before modify() d.height = 10
    dim = 11
    After modify() d.height = 11
    

    Notice when the Dimension object on line 4 is passed to the modify() method, any changes to the object that occur inside the method are being made to the object whose reference was passed. In the preceding example, reference variables d and dim both point to the same object.

    Does Java Use Pass-By-Value Semantics?

    If Java passes objects by passing the reference variable instead, does that mean Java uses pass-by-reference for objects? Not exactly, although you'll often hear and read that it does. Java is actually pass-by-value for all variables running within a single VM. Pass-by-value means pass-by-variable-value. And that means, pass-by-copy-of- the-variable! (There's that word copy again!)

    It makes no difference if you're passing primitive or reference variables, you are always passing a copy of the bits in the variable. So for a primitive variable, you're passing a copy of the bits representing the value. For example, if you pass an int variable with the value of 3, you're passing a copy of the bits representing 3. The called method then gets its own copy of the value, to do with it what it likes.

    And if you're passing an object reference variable, you're passing a copy of the bits representing the reference to an object. The called method then gets its own copy of the reference variable, to do with it what it likes. But because two identical reference variables refer to the exact same object, if the called method modifies the object (by invoking setter methods, for example), the caller will see that the object the caller's original variable refers to has also been changed. In the next section, we'll look at how the picture changes when we're talking about primitives.

    The bottom line on pass-by-value: the called method can't change the caller's variable, although for object reference variables, the called method can change the object the variable referred to. What's the difference between changing the variable and changing the object? For object references, it means the called method can't reassign the caller's original reference variable and make it refer to a different object, or null. For example, in the following code fragment,

            void bar() {
               Foo f = new Foo();
               doStuff(f);
            }
            void doStuff(Foo g) {
               g.setName("Boo");
               g = new Foo();
            }
    

    reassigning g does not reassign f! At the end of the bar() method, two Foo objects have been created, one referenced by the local variable f and one referenced by the local (argument) variable g. Because the doStuff() method has a copy of the reference variable, it has a way to get to the original Foo object, for instance to call the setName() method. But, the doStuff() method does not have a way to get to the f reference variable. So doStuff() can change values within the object f refers to, but doStuff() can't change the actual contents (bit pattern) of f. In other words, doStuff() can change the state of the object that f refers to, but it can't make f refer to a different object!

    Passing Primitive Variables

    Let's look at what happens when a primitive variable is passed to a method:

    class ReferenceTest {
        public static void main (String [] args) {
          int a = 1;
          ReferenceTest rt = new ReferenceTest();
          System.out.println("Before modify() a = " + a);
          rt.modify(a);
          System.out.println("After modify() a = " + a);
        }
        void modify(int number) {
          number = number + 1;
          System.out.println("number = " + number);
        }
    }
    

    In this simple program, the variable a is passed to a method called modify(), which increments the variable by 1. The resulting output looks like this:

      Before modify() a = 1
      number = 2
      After modify() a = 1
    

    Notice that a did not change after it was passed to the method. Remember, it was a copy of a that was passed to the method. When a primitive variable is passed to a method, it is passed by value, which means pass-by-copy-of-the-bits-in-the-variable.

    JasonG

    Posted 2008-09-02T20:14:29.270

    Reputation: 3 598

    With pass-by-value, as Java is, "caller's variable" doesn't make sense. The actual argument is the evaluation of an expression; a variable need not be involved at all. – Tom Blodget – 2018-07-16T00:28:11.000

    7

    There is a very simple way to understand this. Lets's take C++ pass by reference.

    #include <iostream>
    using namespace std;
    
    class Foo {
        private:
            int x;
        public:
            Foo(int val) {x = val;}
            void foo()
            {
                cout<<x<<endl;
            }
    };
    
    void bar(Foo& ref)
    {
        ref.foo();
        ref = *(new Foo(99));
        ref.foo();
    }
    
    int main()
    {
       Foo f = Foo(1);
       f.foo();
       bar(f);
       f.foo();
    
       return 0;
    }
    

    What is the outcome?

    1
    1
    99
    99
    

    So, after bar() assigned a new value to a "reference" passed in, it actually changed the one which was passed in from main itself, explaining the last f.foo() call from main printing 99.

    Now, lets see what java says.

    public class Ref {
    
        private static class Foo {
            private int x;
    
            private Foo(int x) {
                this.x = x;
            }
    
            private void foo() {
                System.out.println(x);
            }
        }
    
        private static void bar(Foo f) {
            f.foo();
            f = new Foo(99);
            f.foo();
        }
    
        public static void main(String[] args) {
            Foo f = new Foo(1);
            System.out.println(f.x);
            bar(f);
            System.out.println(f.x);
        }
    
    }
    

    It says:

    1
    1
    99
    1
    

    Voilà, the reference of Foo in main that was passed to bar, is still unchanged!

    This example clearly shows that java is not the same as C++ when we say "pass by reference". Essentially, java is passing "references" as "values" to functions, meaning java is pass by value.

    Ravi Sanwal

    Posted 2008-09-02T20:14:29.270

    Reputation: 327

    7

    It's a bit hard to understand, but Java always copies the value - the point is, normally the value is a reference. Therefore you end up with the same object without thinking about it...

    Harald Schilly

    Posted 2008-09-02T20:14:29.270

    Reputation: 939

    6

    Everything is passed by value. Primitives and Object references. But objects can be changed, if their interface allows it.

    When you pass an object to a method, you are passing a reference, and the object can be modified by the method implementation.

    void bithday(Person p) {
        p.age++;
    }
    

    The reference of the object itself, is passed by value: you can reassign the parameter, but the change is not reflected back:

    void renameToJon(Person p) { 
        p = new Person("Jon"); // this will not work
    }
    
    jack = new Person("Jack");
    renameToJon(jack);
    sysout(jack); // jack is unchanged
    

    As matter of effect, "p" is reference (pointer to the object) and can't be changed.

    Primitive types are passed by value. Object's reference can be considered a primitive type too.

    To recap, everything is passed by value.

    Luigi R. Viggiano

    Posted 2008-09-02T20:14:29.270

    Reputation: 6 075

    6

    Shortest answer :)

    • Java has pass-by-value (and pass-reference-by-value.)
    • C# also has pass-by-reference

    In C# this is accomplished with the "out" and "ref" keywords.

    Pass By Reference: The variable is passed in such a way that a reassignment inside the method is reflected even outside the method.

    Here follows an example of passing-by-reference (C#). This feature does not exist in java.

    class Example
    {
        static void InitArray(out int[] arr)
        {
            arr = new int[5] { 1, 2, 3, 4, 5 };
        }
    
        static void Main()
        {
            int[] someArray;
            InitArray(out someArray);
    
            // This is true !
            boolean isTrue = (someArray[0] == 1);
        }
    }
    

    See also: MSDN library (C#): passing arrays by ref and out

    See also: MSDN library (C#): passing by by value and by reference

    bvdb

    Posted 2008-09-02T20:14:29.270

    Reputation: 7 236

    in java we can do: someArray = InitArray(someArray) assuming we have this: static int [] InitArray( int[] arr){ ... return ...} – Kachna – 2016-02-27T11:06:27.997

    You are correct. That's a possible alternative for a simple pass-by-reference. But pass-by-reference can do more powerful things. e.g. it could assign multiple values: e.g. int[] array1; int[] array2; InnitArrays(out array1, out array2); assuming that you create a method static void InitArray(out int[] a1, out int[] a2){...} – bvdb – 2016-02-27T16:28:14.093

    6

    Simple program

    import java.io.*;
    class Aclass
    {
        public int a;
    }
    public class test
    {
        public static void foo_obj(Aclass obj)
        {
            obj.a=5;
        }
        public static void foo_int(int a)
        {
            a=3;
        }
        public static void main(String args[])
        {
            //test passing an object
            Aclass ob = new Aclass();
            ob.a=0;
            foo_obj(ob);
            System.out.println(ob.a);//prints 5
    
            //test passing an integer
            int i=0;
            foo_int(i);
            System.out.println(i);//prints 0
        }
    }
    

    From a C/C++ programmer's point of view, java uses pass by value, so for primitive data types (int, char etc) changes in the function does not reflect in the calling function. But when you pass an object and in the function you change its data members or call member functions which can change the state of the object, the calling function will get the changes.

    Ramprasad

    Posted 2008-09-02T20:14:29.270

    Reputation: 45

    1You can only define one class per file. This is not including nested and inner classes. Considering this will be something a new programmer will be reading, you should explain this to the user; allowing them to duplicate the code on their machine. – mrres1 – 2015-01-25T01:30:21.983

    2@mrres1 Not entirely correct. You can define only one public top-level class/interface per file. Supporting several classes per file is a remnant from the first Java version, which didn't have nested classes, but it is still supported, though often frowned upon. – MrBackend – 2015-03-19T13:53:06.450

    6

    Unlike some other languages, Java does not allow you to choose pass-by-value or pass-by-reference

    all arguments are passed by value.

    A method call can pass two types of valuesto a method

    • copies of primitive values (e.g., values of type int and double)
    • copies of references to objects.

    Objects themselves cannot be passed to methods. When a method modifies a primitive-type parameter, changes to the parameter have no effect on the original argument value in the calling method.

    This is also true for reference-type parameters. If you modify a reference-type parameter so that it refers to another object, only the parameter refers to the new object—the reference stored in the caller’s variable still refers to the original object.

    References: Java™ How To Program (Early Objects), Tenth Edition

    Basheer AL-MOMANI

    Posted 2008-09-02T20:14:29.270

    Reputation: 6 063

    6

    Java is pass by value.

    There are already great answers on this thread. Somehow, I was never clear on pass by value/reference with respect to primitive data types and with respect to objects. Therefore, I tested it out for my satisfaction and clarity with the following piece of code; might help somebody seeking similar clarity:

    class Test    {
    
    public static void main (String[] args) throws java.lang.Exception
    {
        // Primitive type
        System.out.println("Primitve:");
        int a = 5;
        primitiveFunc(a);
        System.out.println("Three: " + a);    //5
    
        //Object
        System.out.println("Object:");
        DummyObject dummyObject = new DummyObject();
        System.out.println("One: " + dummyObject.getObj());    //555
        objectFunc(dummyObject);
        System.out.println("Four: " + dummyObject.getObj());    //666 (555 if line in method uncommented.)
    
    }
    
    private static void primitiveFunc(int b)    {
        System.out.println("One: " + b);    //5
        b = 10;
        System.out.println("Two:" + b);    //10
    }
    
    private static void objectFunc(DummyObject b)   {
        System.out.println("Two: " + b.getObj());    //555
        //b = new DummyObject();
        b.setObj(666);
        System.out.println("Three:" + b.getObj());    //666
    }
    
    }
    
    class DummyObject   {
        private int obj = 555;
        public int getObj() { return obj; }
        public void setObj(int num) { obj = num; }
    }
    

    If the line b = new DummyObject() is uncommented, the modifications made thereafter are made on a new object, a new instantiation. Hence, it is not reflected in the place where the method is called from. However, otherwise, the change is reflected as the modifications are only made on a "reference" of the object, i.e - b points to the same dummyObject.

    Illustrations in one of the answers in this thread (https://stackoverflow.com/a/12429953/4233180) can help gain a deeper understanding.

    Supriya

    Posted 2008-09-02T20:14:29.270

    Reputation: 627

    6

    • passed by reference : caller and callee use same variable for parameter.

    • passed by value : caller and callee have two independent variables with same value.

    • Java uses pass by value
      • When passing primitive data, it copies the value of primitive data type.
      • When passing object, it copies the address of object and passes to callee method variable.

    Example using primitive data type:

    public class PassByValuePrimitive {
        public static void main(String[] args) {
            int i=5;
            System.out.println(i);  //prints 5
            change(i);
            System.out.println(i);  //prints 5
        }
    
    
        private static void change(int i) {
            System.out.println(i);  //prints 5
            i=10;
            System.out.println(i); //prints 10
    
        }
    }
    

    Example using object:

    public class PassByValueObject {
        public static void main(String[] args) {
            List<String> list = new ArrayList<>();
            list.add("prem");
            list.add("raj");
            new PassByValueObject().change(list);
            System.out.println(list); // prints [prem, raj, ram]
    
        }
    
    
        private  void change(List list) {
            System.out.println(list.get(0)); // prem
            list.add("ram");
            list=null;
            System.out.println(list.add("bheem")); //gets NullPointerException
        }
    }
    

    Premraj

    Posted 2008-09-02T20:14:29.270

    Reputation: 27 989

    6

    PT 1: Of Realty Listings

    There is a blue, 120sq-ft "Tiny House" currently parked at 1234 Main St with a nicely manicured lawn & flower bed out front.

    A Realtor with a local firm is hired and told to keep a listing for that house.

    Let's call that Realtor "Bob." Hi Bob.

    Bob keeps his Listing, which he calls tinyHouseAt1234Main, up to date with a webcam that allows him to note any changes to the actual house in real time. He also keeps a tally of how many people have asked about the listing. Bob's integer viewTally for the house is at 42 today.

    Whenever someone wants info about the blue Tiny House at 1234 Main St, they ask Bob.

    Bob looks up his Listing tinyHouseAt1234Main and tells them all about it - the color, the nice lawn, the loft bed and the composting toilet, etc. Then he adds their inquiry to his viewTally. He doesn't tell them the real, physical address though, because Bob's firm specializes in Tiny Houses that could be moved at any time. The tally is now 43.

    At another firm, Realtors might explicitly say their listing "points" to the house at 1234 Main St, denoting this with a little * next to it, because they mainly deal with houses that rarely ever move (though presumably there are reasons for doing so). Bob's firm doesn't bother doing this.

    Now, of course Bob doesn't physically go and put the actual house on a truck to show it to clients directly - that would be impractical and a ridiculous waste of resources. Passing a full copy of his tally sheet is one thing, but passing around the whole house all the time is costly and ridiculous.

    (Aside: Bob's firm also doesn't 3D print new & unique copies of a listed house every single time someone asks about it. That's what the upstart, similarly named web-based firm & its spinoffs do - that's expensive and slower, and people often get the 2 firms confused, but they're quite popular anyway).

    At some other, older firms closer to the Sea, a realtor like Bob might not even exist to manage the Listings. Clients might instead consult the Rolodex "Annie" (& for short) for the direct address of the house. Instead of reading off the referenced house details from the listing like Bob does, clients instead get the house address from Annie (&), and go directly to 1234 Main St, sometimes w/no idea what they might find there.

    One day, Bob's firm begins offering a new automated service that needs the listing for a house the client is interested in.

    Well, the person with that info is Bob, so the client has Bob call up the service and send it a copy of the listing.

    jobKillingAutomatedListingService(Listing tinyHouseAt1234Main, int viewTally) Bob sends along ...

    The service, on its end, calls this Listing houseToLookAt, but really what it receives is an exact copy of Bob's listing, with the exact same VALUEs in it, that refer to the house at 1234 Main St.

    This new service also has its own internal tally of how many people have viewed the listing. The service accepts Bob's tally out of professional courtesy, but it doesn't really care and overwrites it entirely with its own local copy anyway. It's tally for today is 1, while Bob's is still 43.

    The realty firms call this "pass-by-value" since Bob's passing the current value of his viewTally and his Listing tinyHouseAt1234Main. He's not actually passing along the entire physical house, because that's impractical. Nor is he passing the real physical address like Annie(&) would do.

    But he IS passing a copy of the value OF the reference he has to the house. Seems like a silly pedantic difference in some ways, but that's how his firm works ... ..............

    PT II: Where things get confusing and dangerous ...

    The new automated service, not being all functional and math-oriented like some other trendy financial & scientific firms, can have unforeseen side effects...

    Once given a Listing object it allows clients to actually repaint the REAL house at 1234 Main St, using a remote drone robot fleet! It allows clients to control a robot bulldozer to ACTUALLY dig up the flower bed! This is madness!!!

    The service also lets clients completely redirect houseToLookAt to some other house at another address, without involving Bob or his listing. All of a sudden they could be looking at 4321 Elm St. instead, which has no connection whatsoever to Bob's listing (thankfully they can't do anymore damage).

    Bob watches all this on his realtime webcam. Resigned to the drudgery of his sole job responsibility, he tells clients about the new ugly paint job & sudden lack of curb appeal. His Listing is still for 1234 Main St., after all. The new service's houseToLookAt couldn't change that. Bob reports the details of his tinyHouseAt1234Main accurately and dutifully as always, until he gets fired or the house is destroyed entirely by The Nothing.

    Really the only thing the service CAN'T do with its houseToLookAt copy of the Bob's original listing is change the address from 1234 Main St. to some other address, or to a void of nothingness, or to some random type of object like a Platypus. Bob's Listing still always points to 1234 Main St, for whatever it's still worth. He passes its current value around like always.

    This bizarre side-effect of passing a listing to the new automated service is confusing for people who ask about how it works. Really, what's the difference between the ability to remotely control robots that alter the state of the house at 1234 Main, vs. actually physically going there and wreaking havoc because Annie gave you the address??

    Seems like kind of a nitpicky semantic argument if what you generally care about is the state of the house in the listing being copied and passed around, right?

    I mean, if you were in the business of actually picking up houses and physically moving them to other addresses (not like mobile or Tiny Homes where that's sort of an expected function of the platform), or you were accessing, renaming, and shuffling entire neighborhoods like some sort of low-level God-playing madman, THEN maybe you'd care more about passing around those specific address references instead of just copies of the the latest value of the house details ...

    mc01

    Posted 2008-09-02T20:14:29.270

    Reputation: 3 060

    6

    In my opinion, "pass by value" is a terrible way to singularly describe two similar but different events. I guess they should have asked me first.

    With primitives we are passing the actual value of the primitive into the method (or constructor), be it the integer "5", the character "c", or what have you. That actual value then becomes its own local primitive. But with objects, all we are doing is giving the same object an additional reference (a local reference), so that we now have two references pointing to the same object.

    I hope this simple explanation helps.

    Swifty McSwifterton

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 962

    4'Pass by value' is a standard term in computer science and has been since the 1950s. No point in complaining about it now. – user207421 – 2016-06-07T03:59:03.743

    5

    Java passes parameters by value, but for object variables, the values are essentially references to objects. Since arrays are objects the following example code shows the difference.

    public static void dummyIncrease(int[] x, int y)
    {
        x[0]++;
        y++;
    }
    public static void main(String[] args)
    {
        int[] arr = {3, 4, 5};
        int b = 1;
        dummyIncrease(arr, b);
        // arr[0] is 4, but b is still 1
    }
    
    main()
      arr +---+       +---+---+---+
          | # | ----> | 3 | 4 | 5 |
          +---+       +---+---+---+
      b   +---+             ^
          | 1 |             | 
          +---+             |
                            |
    dummyIncrease()         |
      x   +---+             |
          | # | ------------+
          +---+      
      y   +---+ 
          | 1 | 
          +---+ 
    

    user1931858

    Posted 2008-09-02T20:14:29.270

    Reputation: 7 070

    4

    Java is always pass-by-value, the parameters are copies of what the variables passed, all Objects are defined using a reference, and reference is a variable that stores a memory address of where the object is in memory.

    Check the comments to understand what happens in execution; follow numbers as they show the flow of execution ..

    class Example
    {
        public static void test (Cat ref)
        {
            // 3 - <ref> is a copy of the reference <a>
            // both currently reference Grumpy
            System.out.println(ref.getName());
    
            // 4 - now <ref> references a new <Cat> object named "Nyan"
            ref = new Cat("Nyan");
    
            // 5 - this should print "Nyan"
            System.out.println( ref.getName() );
        }
    
        public static void main (String [] args)
        {
            // 1 - a is a <Cat> reference that references a Cat object in memory with name "Grumpy"
            Cat a = new Cat("Grumpy");
    
            // 2 - call to function test which takes a <Cat> reference
            test (a);
    
            // 6 - function call ends, and <ref> life-time ends
            // "Nyan" object has no references and the Garbage
            // Collector will remove it from memory when invoked
    
            // 7 - this should print "Grumpy"
            System.out.println(a.getName());
        }
    }
    

    Khaled.K

    Posted 2008-09-02T20:14:29.270

    Reputation: 5 052

    'Pass its inner value' is meaningless. – user207421 – 2017-09-17T10:09:47.717

    @EJP thanks for the note, excuse my bad English from 2013, I've edited the whole thing, if you see a better wording, you may suggest or edit – Khaled.K – 2017-09-17T16:41:46.070

    i would like to add one thing.if you have changed the name of cat instead of creating a new one, it will reflect in the memory even after the method returns – None – 2017-11-18T16:26:37.253

    4

    Mr @Scott Stanchfield wrote an excellent answer. Here is the class that would you to verify exactly what he meant:

    public class Dog {
    
        String dog ;
        static int x_static;
        int y_not_static;
    
        public String getName()
        {
            return this.dog;
        }
    
        public Dog(String dog)
        {
            this.dog = dog;
        }
    
        public void setName(String name)
        {
            this.dog = name;
        }
    
        public static void foo(Dog someDog)
        {
            x_static = 1;
            // y_not_static = 2;  // not possible !!
            someDog.setName("Max");     // AAA
            someDog = new Dog("Fifi");  // BBB
            someDog.setName("Rowlf");   // CCC
        }
    
        public static void main(String args[])
        {
            Dog myDog = new Dog("Rover");
            foo(myDog);
            System.out.println(myDog.getName());
        }
    }
    

    So, we pass from main() a dog called Rover, then we assign a new address to the pointer that we passed, but at the end, the name of the dog is not Rover, and not Fifi, and certainly not Rowlf, but Max.

    ron

    Posted 2008-09-02T20:14:29.270

    Reputation: 8 008

    4

    Understand it in 2 Steps:

    You can't change the reference to the object itself but you can work with this passed parameter as a reference to the object.

    If you want to change the value behind the reference you will only declare a new variable on the stack with the same name 'd'. Look at the references with the sign @ and you will find out that the reference has been changed.

    public static void foo(Dog d) {
      d.Name = "belly";
      System.out.println(d); //Reference: [email protected]
    
      d = new Dog("wuffwuff");
      System.out.println(d); //[email protected]
    }
    public static void main(String[] args) throws Exception{
      Dog lisa = new Dog("Lisa");
      foo(lisa);
      System.out.println(lisa.Name); //belly
    }
    

    Dustin Deus

    Posted 2008-09-02T20:14:29.270

    Reputation: 93

    4

    I tried to simplify the examples above, keeping only the essense of the problem. Let me present this as a story that is easy to remember and apply correctly. The story goes like this: You have a pet dog, Jimmy, whose tail is 12 inches long. You leave it with a vet for a few weeks while you are travelling abroad.

    The vet doesn't like the long tail of Jimmy, so he wants to cut it by half. But being a good vet, he knows that he has no right to mutilate other people's dogs. So he first makes a clone of the dog (with the new key word) and cuts the tail of the clone. When the dog finally returns to you, it has the original 12 inch tail in tact. Happy ending !

    The next time you travel, you take the dog, unwittingly, to a wicked vet. He is also a hater of long tails, so he cuts it down to a miserable 2 inches. But he does this to your dear Jimmy, not a clone of it. When you return, you are shocked to see Jimmy pathetically wagging a 2 inch stub.

    Moral of the story: When you pass on your pet, you are giving away whole and unfettered custody of the pet to the vet. He is free to play any kind of havoc with it. Passing by value, by reference, by pointer are all just technical wrangling. Unless the vet clones it first, he ends up mutilating the original dog.

    public class Doggie {
    
        public static void main(String...args) {
            System.out.println("At the owner's home:");
            Dog d = new Dog(12);
            d.wag();
            goodVet(d);
            System.out.println("With the owner again:)");
            d.wag();
            badVet(d);
            System.out.println("With the owner again(:");
            d.wag();
        }
    
        public static void goodVet (Dog dog) {
            System.out.println("At the good vet:");
            dog.wag();
            dog = new Dog(12); // create a clone
            dog.cutTail(6);    // cut the clone's tail
            dog.wag();
        }
    
        public static void badVet (Dog dog) {
            System.out.println("At the bad vet:");
            dog.wag();
            dog.cutTail(2);   // cut the original dog's tail
            dog.wag();
        }    
    }
    
    class Dog {
    
        int tailLength;
    
        public Dog(int originalLength) {
            this.tailLength = originalLength;
        }
    
        public void cutTail (int newLength) {
            this.tailLength = newLength;
        }
    
        public void wag()  {
            System.out.println("Wagging my " +tailLength +" inch tail");
        }
    }
    
    Output:
    At the owner's home:
    Wagging my 12 inch tail
    At the good vet:
    Wagging my 12 inch tail
    Wagging my 6 inch tail
    With the owner again:)
    Wagging my 12 inch tail
    At the bad vet:
    Wagging my 12 inch tail
    Wagging my 2 inch tail
    With the owner again(:
    Wagging my 2 inch tail
    

    Raja

    Posted 2008-09-02T20:14:29.270

    Reputation: 596

    3

    The bottom line on pass-by-value: the called method can't change the caller's variable, although for object reference variables, the called method can change the object the variable referred to. What's the difference between changing the variable and changing the object? For object references, it means the called method can't reassign the caller's original reference variable and make it refer to a different object, or null.

    I took this code and explanation from a book on Java Certification and made some minor changes.
    I think it's a good illustration to the pass by value of an object. In the code below, reassigning g does not reassign f! At the end of the bar() method, two Foo objects have been created, one referenced by the local variable f and one referenced by the local (argument) variable g.

    Because the doStuff() method has a copy of the reference variable, it has a way to get to the original Foo object, for instance to call the setName() method. But, the doStuff() method does not have a way to get to the f reference variable. So doStuff() can change values within the object f refers to, but doStuff() can't change the actual contents (bit pattern) of f. In other words, doStuff() can change the state of the object that f refers to, but it can't make f refer to a different object!

    package test.abc;
    
    public class TestObject {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            bar();
        }
    
        static void bar() {
            Foo f = new Foo();
            System.out.println("Object reference for f: " + f);
            f.setName("James");
            doStuff(f);
            System.out.println(f.getName());
            //Can change the state of an object variable in f, but can't change the object reference for f.
            //You still have 2 foo objects.
            System.out.println("Object reference for f: " + f);
            }
    
        static void doStuff(Foo g) {
                g.setName("Boo");
                g = new Foo();
                System.out.println("Object reference for g: " + g);
            }
    }
    
    
    package test.abc;
    
    public class Foo {
        public String name = "";
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
    }
    

    Note that the object reference has not changed in the console output below:

    Console output:

    Object reference for f: [email protected]

    Object reference for g: [email protected]

    Boo Object reference for f: [email protected]

    James Drinkard

    Posted 2008-09-02T20:14:29.270

    Reputation: 9 237

    3

    There is a workaround in Java for the reference. Let me explain by this example:

    public class Yo {
    public static void foo(int x){
        System.out.println(x); //out 2
        x = x+2;
        System.out.println(x); // out 4
    }
    public static void foo(int[] x){
        System.out.println(x[0]); //1
        x[0] = x[0]+2;
        System.out.println(x[0]); //3
    }
    public static void main(String[] args) {
        int t = 2;
        foo(t);
        System.out.println(t); // out 2 (t did not change in foo)
    
        int[] tab = new int[]{1};
        foo(tab);
        System.out.println(tab[0]); // out 3 (tab[0] did change in foo)
    }}
    

    I hope this helps!

    drew7721

    Posted 2008-09-02T20:14:29.270

    Reputation: 1 110

    3

    Java passes everything by value!!

    //create an object by passing in a name and age:

    PersonClass variable1 = new PersonClass("Mary", 32);
    
    PersonClass variable2;
    

    //Both variable2 and variable1 now reference the same object

    variable2 = variable1; 
    
    
    PersonClass variable3 = new PersonClass("Andre", 45);
    

    // variable1 now points to variable3

    variable1 = variable3;
    

    //WHAT IS OUTPUT BY THIS?

    System.out.println(variable2);
    System.out.println(variable1);
    
    Mary 32
    Andre 45
    

    if you could understand this example we r done. otherwise, please visit this webPage for detailed explanation:

    webPage

    João Oliveira

    Posted 2008-09-02T20:14:29.270

    Reputation: 112

    This actually doesn't explain anything in regards to potential by ref/by val property of Java. – Mox – 2017-01-18T11:38:31.580

    3

    ACCORDING TO C++ TERMINOLOGY :

    1. Primitive Types and their wrappers - Pass by Value
    2. Other Complex Datatypes - Pass by Reference

    (Although Java is completely Pass by Value, in the second case it passes the reference to the object and in this case the value of the object if changed is reflected in the main function and so I called it Pass by Reference according to C++ Terminology.) If you are hailing from C++, then Java is pass by value for Primitive types and their Wrapper Classes like int, Integer, bool, Boolean i.e., if you pass a value of these data types, there will be no change in the original function. For all other kinds of datatypes java just passes them and if any change is made, the change can be seen in the original function(It can be called pass by reference according to c++ terminology)

    kaushalpranav

    Posted 2008-09-02T20:14:29.270

    Reputation: 491

    3

    I made this little diagram that shows how the data gets created and passed

    Diagram of how data is created and passed

    Note: Primitive values are passed as a value, the first reference to to that value is the method's argument

    That means:

    • You can change the value of myObject inside the function
    • But you can't change what myObject references to, inside the function, because point is not myObject
    • Remember, both point and myObject are references, different references, however, those references point at the same new Point(0,0)

    OverCoder

    Posted 2008-09-02T20:14:29.270

    Reputation: 656

    3

    A lot of the confusion surrounding this issue comes from the fact that Java has attempted to redefine what "Pass by value" and "Pass by reference" mean. It's important to understand that these are Industry Terms, and cannot be correctly understood outside of that context. They are meant to help you as you code and are valuable to understand, so let's first go over what they mean.

    A good description of both can be found here.

    Pass By Value The value the function received is a copy of the object the caller is using. It is entirely unique to the function and anything you do to that object will only be seen within the function.

    Pass By Reference The value the function received is a reference to the object the caller is using. Anything the function does to the object that value refers to will be seen by the caller and it will be working with those changes from that point on.

    As is clear from those definitions, the fact that the reference is passed by value is irrelevant. If we were to accept that definition, then these terms become meaningless and all languages everywhere are only Pass By Value.

    No matter how you pass the reference in, it can only ever be passed by value. That isn't the point. The point is that you passed a reference to your own object to the function, not a copy of it. The fact that you can throw away the reference you received is irrelevant. Again, if we accepted that definition, these terms become meaningless and everyone is always passing by value.

    And no, C++'s special "pass by reference" syntax is not the exclusive definition of pass by reference. It is purely a convenience syntax meant to make it so that you don't need to use pointer syntax after passing the pointer in. It is still passing a pointer, the compiler is just hiding that fact from you. It also still passes that pointer BY VALUE, the compiler is just hiding that from you.

    So, with this understanding, we can look at Java and see that it actually has both. All Java primitive types are always pass by value because you receive a copy of the caller's object and cannot modify their copy. All Java reference types are always pass by reference because you receive a reference to the caller's object and can directly modify their object.

    The fact that you cannot modify the caller's reference has nothing to do with pass by reference and is true in every language that supports pass by reference.

    Cdaragorn

    Posted 2008-09-02T20:14:29.270

    Reputation: 337

    3

    Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

    Take the badSwap() method for example:

        public void badSwap(int var1, int
     var2{ int temp = var1; var1 = var2; var2 =
     temp; }
    

    When badSwap() returns, the variables passed as arguments will still hold their original values. The method will also fail if we change the arguments type from int to Object, since Java passes object references by value as well. Now, here is where it gets tricky:

    public 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("X:
     " + pnt1.x + " Y: " +pnt1.y);
    
         System.out.println("X: " + pnt2.x + " Y:
     " +pnt2.y); System.out.println(" ");
    
         tricky(pnt1,pnt2);
     System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
    
         System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); }
    

    If we execute this main() method, we see the following output:

    X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0

    The method successfully alters the value ofpnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In themain() method, pnt1 and pnt2 are nothing more than object references. When you passpnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.

    Java copies and passes the reference by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.

    Vivek Kumar

    Posted 2008-09-02T20:14:29.270

    Reputation: 139

    3

    It seems everything is call by value in java as i have tried to understand by the following program

    Class-S

    class S{
    String name="alam";
    public void setName(String n){
    this.name=n; 
    }}
    

    Class-Sample

        public class Sample{
        public static void main(String args[]){
        S s=new S();
        S t=new S();
        System.out.println(s.name);
        System.out.println(t.name);
        t.setName("taleev");
        System.out.println(t.name);
        System.out.println(s.name);
        s.setName("Harry");
        System.out.println(t.name);
        System.out.println(s.name);
        }}
    

    Output

    alam

    alam

    taleev

    alam

    taleev

    harry

    As we have define class S with instance variable name with value taleev so for all the objects that we initialize from it will have the name variable with value of taleev but if we change the name's value of any objects then it is changing the name of only that copy of the class(Object) not for every class so after that also when we do System.out.println(s.name) it is printing taleev only we can not change the name's value that we have defined originally, and the value that we are changing is the object's value not the instance variable value so once we have define instance variable we are unable to change it

    So i think that is how it shows that java deals with values only not with the references

    The memory allocation for the primitive variables can be understood by this

    Taleev Aalam

    Posted 2008-09-02T20:14:29.270

    Reputation: 9

    3

    The term call by value means that the method gets just the value the caller provides. In contrast, call by reference means that the method gets the location(address) of the variable that the caller provides.

    The Java programming language always uses call by value. That means that the method gets a copy of all parameter values. In particular, it is totally true that the method cannot modify the contents(the value of the address: something like @e48e1b ) of any reference object passed to it, but it can modify its state.

    The reason is simple. The method gets a copy of the object reference or the value of the object address, and both the original and the copy refer to the same object.

    hamza belmellouki

    Posted 2008-09-02T20:14:29.270

    Reputation: 86

    2

    Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.

    Learner

    Posted 2008-09-02T20:14:29.270

    Reputation: 14

    2

    Easy answer for beginner

    If you pass a complex Object (like a dog as apparently it is the common example) it is the same as passing the reference. If you pass a field of a complex Object (like the name of the dog only) it is the same as passing the value (changing it won't change the dog/parent of the field).

    Note that Object that are not "complex" (not like our dog) like Integer or String are passed by value. So even if they are Object with everything you can do on them they cannot be modified inside a method... Yes, this is ****ed up and does not make any sense...

    Example (not a Dog) :

    public class HelloWorld {
        private Integer i;
        private String s;
        private Boolean b;
    
        public static void main(String[] args) {
            HelloWorld h = new HelloWorld();
    
            h.s = "Bill";
            h.ModMe(h.s);
            h.i = 2;
            h.ModMe(h.i);
            h.b = true;
            h.ModMe(h.b);
            System.out.println(h.s + " " + h.i + " " + h.b);
    
            h.ModMe(h);
            System.out.println(h.s + " " + h.i + " " + h.b);
    
            String test = "TEST";
            h.ModMe(test);
            System.out.println(test);
        }
    
        public void ModMe(Object o) {
            if (o instanceof HelloWorld) {
                ((HelloWorld) o).i = (int) Math.pow(((HelloWorld) o).i, 2);
                ((HelloWorld) o).b = !((HelloWorld) o).b;
                ((HelloWorld) o).s = ((HelloWorld) o).s.concat(" modded successfully");
            } else if (o instanceof Integer) {
                o = (Integer) o + (Integer) o;
            } else if (o instanceof String) {
                o = ((String) o).concat(" is modified.");
            } else if (o instanceof Boolean) {
                o = !(Boolean) o;
            }
        }
    }
    

    If you run that the object h will be modified if you use the whole object as the argument but not the fields s i or b if you only use them as argument. if you debug that you will notice that for the fields the id of the object will change as soon as you run the line where the value is changed. So it will do the same as "new Integer" "new String" and "new Boolean" automatically.

    CodeKiller

    Posted 2008-09-02T20:14:29.270

    Reputation: 45

    1

    The Java programming language passes arguments only by value, that is, you cannot change the argument value in the calling method from within the called method.


    However, when an object instance is passed as an argument to a method, the value of the argument is not the object itself but a reference to the object. You can change the contents of the object in the called method but not the object reference.


    To many people, this looks like pass-by-reference, and behaviorally, it has much in common with pass-by-reference. However, there are two reasons this is inaccurate.

    • Firstly, the ability to change the thing passed into a method only applies to objects, not primitive values.

    • Second, the actual value associated with a variable of object type is the reference to the object, and not the object itself. This is an important distinction in other ways, and if clearly understood, is entirely supporting of the point that the Java programming language passes arguments by value.


    The following code example illustrates this point:
    1 public class PassTest {
    2
    3   // Methods to change the current values
    4   public static void changeInt(int value) {
    5     value = 55;
    6  }
    7   public static void changeObjectRef(MyDate ref) {
    8     ref = new MyDate(1, 1, 2000);
    9  }
    10   public static void changeObjectAttr(MyDate ref) {
    11     ref.setDay(4);
    12   }
    13
    14 public static void main(String args[]) {
    15     MyDate date;
    16     int val;
    17
    18     // Assign the int
    19     val = 11;
    20     // Try to change it
    21     changeInt(val);
    22     // What is the current value?
    23     System.out.println("Int value is: " + val);
    24
    25 // Assign the date
    26     date = new MyDate(22, 7, 1964);
    27     // Try to change it
    28     changeObjectRef(date);
    29     // What is the current value?
    30 System.out.println("MyDate: " + date);
    31
    32 // Now change the day attribute
    33     // through the object reference
    34     changeObjectAttr(date);
    35     // What is the current value?
    36 System.out.println("MyDate: " + date);
    37   }
    38 }
    

    This code outputs the following:
    java PassTest
    Int value is: 11
    MyDate: 22-7-1964
    MyDate: 4-7-1964
    The MyDate object is not changed by the changeObjectRef method;
    however, the changeObjectAttr method changes the day attribute of the
    MyDate object.
    

    Bhushan

    Posted 2008-09-02T20:14:29.270

    Reputation: 265

    This is very misleading. You certainly can change the value of an argument from within a method. – Gray – 2017-11-28T20:33:54.387

    1

    Java passes references to objects by value.

    So if any modification is done to the Object to which the reference argument points it will be reflected back on the original object.

    But if the reference argument point to another Object still the original reference will point to original Object.

    Aniket Thakur

    Posted 2008-09-02T20:14:29.270

    Reputation: 40 617

    1

    Java is only passed by value. there is no pass by reference, for example, you can see the following example.

    package com.asok.cop.example.task;
    public class Example {
        int data = 50;
    
        void change(int data) {
            data = data + 100;// changes will be in the local variable 
            System.out.println("after add " + data);
            }
    
        public static void main(String args[]) {
            Example op = new Example();
            System.out.println("before change " + op.data);
            op.change(500);
            System.out.println("after change " + op.data);
        }
    }
    

    Output:

    before change 50
    after add 600
    after change 50
    

    asok

    Posted 2008-09-02T20:14:29.270

    Reputation: 121

    0

    TL;DR: Minimal example:

    package foobar;
    import java.util.ArrayList;
    
    public class FooBar {
    
      public static void main(String[] args) {
        ArrayList<Integer> list1 = new ArrayList<>(); // An object.
        list1.add(1);
    
        ArrayList<Integer> list2 = new ArrayList<>(); // Another object.
        list2.add(2);
    
        int x = 42; // A primitive (same with Integer).
    
        sideEffects(list1, list2, x);
    
        System.out.println(list1); // Output: [1]     (unchanged)
        System.out.println(list2); // Output: [2, 3]  (changed !)
        System.out.println(x);     // Output: 42      (not changed)
      }
    
      private static void sideEffects(ArrayList<Integer> list1, ArrayList<Integer> list2, int x) {
        list1 = list2;
        list1.add(3);
        x = 21;
      }
    }
    

    Christophe Roussy

    Posted 2008-09-02T20:14:29.270

    Reputation: 8 948

    -4

    public static void main(String args[]) {
    
        Point p1 = new Point(1, 1); //This is pointing to a location in memory let's say that the reference is x1=5
        Point p2 = new Point(2, 2); //This is pointing to a location in memory let's say that the reference is x2=6
    
        // Next we need to pass something to the function, what is it and how we pass it? 
        // There are two references x1,x2 are going to be passed by value
        // Meaning that if x1=5, x2=6 as we mentioned, we are passing 5,6. We are not passing x1,x2
        // That's a big difference. If we are passing x1 and x2, we can change values there inside the trickMe method.
        // but we are passing only two numbers which are 5 and 6.
        trickMe(p1, p2);
    
        System.out.println(p1); // outputs java.awt.Point[x=1,y=1]
        System.out.println(p2); // outputs java.awt.Point[x=2,y=2]
    }
    
    //  Here we received two values which are 5,6.
    // This method will create another two references which are x3,x4 for objects arg3,arg4
    // arg3 and arg4 are actually same exact objects as p1,p2 with the same memory location. 
    // BUT we use x1,x2 to access p1,p2
    // AND we use x3,x4 to access arg3,arg4
    // x3 is corresponding to x1 and each one of them equal 5. Each one of them means that they are not the same obviously, but have equal values.
    // x4 is corresponding to x2 and each one of them equal 6.
    // Beautiful, now if we replace x3 with x4,, does this replace  x1 with x2?
    // NO THEY ARE TOTALLY INDEPENDENT. x3 and x4 are inside the trickMe Method. they have no acces to x1,x2 at all.
    // So, no matter what I did to x3,x4 inside the trickMe method, x1 and x2 in the main method will not change at all.
    // They will remain x1=5 and x2=6
    public static void trickMe(Point arg3, Point arg4) {
        // Now we have a reference to arg3 which is x3 and it is equal to 5 and a reference to arg4 which is x4 and equal to 6, right?
        // Great! When we say arg3=arg4, we means that make the reference of arg3 which is x3 equals to the reference of arg4 which is x4.
        // Meaning, from this point,, we will make x3=6 instead of 5 and of course x4 is still 6 as it was.
        // We didn't touch niether x1 nor x2, we also can't thouch them inside trickMe method.
        // We only have access to x3 and x4.
        // That's why swapping methods always fail in java if we just put the equal sign "=" to swap.
        // We really have two memory locations which represents two, but with 4 different refernces.
        // Two are in the main method, and another two are in this method
        arg3 = arg4;
    }
    

    Ahmed Abouhegaza

    Posted 2008-09-02T20:14:29.270

    Reputation: 94