By user4315

2008-09-02 20:14:29 8 Comments

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?


@Eng.Fouad 2012-09-14 18:22:55

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

I will explain this in steps:

  1. Declaring a reference named f of type Foo and assign it 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 null.

    public static void changeReference(Foo a)

    enter image description here

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


    enter image description here

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

    Foo b = new Foo("b");

    enter image description here

  5. a = b makes a new assignment to the reference a, not f, of 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 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 :)

@DaveM 2013-06-07 08:46:12

+1 Nice stuff. good diagrams. I also found a nice succinct page here 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).

@Mr D 2013-07-15 19:08:28

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

@Mike Braun 2013-12-01 13:02:34

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

@Evil Washing Machine 2014-11-18 11:34:58

@MikeBraun ...what? Now you've confused me :S. Isn't what you just wrote contrary to what 6. and 7. shows?

@Mike Braun 2014-11-18 19:17:10

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

@Evil Washing Machine 2014-11-20 14:18:52

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

@MaxZoom 2015-02-11 05:19:14

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.

@herbertD 2015-08-08 15:21:12

The setAttribute method need to be accessed by Java reflection.…

@Cdaragorn 2016-05-06 20:36:52

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.

@allenwang 2016-05-21 12:38:43

This is the best explanation I've found. By the way, what about the basic situation? For example, the argument requires an int type, does it still pass the copy of an int variable to the argument?

@The_Martian 2017-12-09 03:17:21

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?

@fishinear 2019-01-14 23:34:30

@The_Martian You are correct, the variable a is assigned the current value of b, or in other words, the value of b is assigned to the variable a. I have changed the language now, to correctly reflect what happens.

@erlando 2008-09-02 20:25:37

Java is always pass-by-value. Unfortunately, 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");
    Dog oldDog = aDog;

    // we pass the object to foo
    // aDog variable is still pointing to the "Max" dog when foo(...) returns
    aDog.getName().equals("Max"); // true
    aDog.getName().equals("Fifi"); // false
    aDog == oldDog; // true

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.


public static void main(String[] args) {
    Dog aDog = new Dog("Max");
    Dog oldDog = aDog;

    // when foo(...) returns, the name of the dog has been changed to "Fifi"
    aDog.getName().equals("Fifi"); // true
    // but it is still the same dog:
    aDog == oldDog; // true

public static void foo(Dog d) {
    d.getName().equals("Max"); // true
    // this changes the name of d to be "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, but it is not possible to change the value of the variable aDog itself.

@izb 2008-09-08 14:58:53

Isn't it slightly confusing the issue with internal details? There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'.

@erlando 2008-09-11 06:55:48

But there is a subtle difference. Look at the first example. If it was purely pass by reference, 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.

@Lorenzo Boccaccia 2008-11-26 17:50:54

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

@Esko Luontola 2009-02-12 23:02:20

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

@dhackner 2010-10-20 16:38:55

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

@Ishmael 2011-02-02 21:10:46

Your point might be clearer if the name passed to the constructor was different than the name used in the foo method.

@Prof. Falken 2011-02-09 09:46:44

What's confusing is that object references are actually pointers. In the beginning SUN called them pointers. Then marketing informed that "pointer" was a bad word. But you still see the "correct" nomenclature in NullPointerException.

@Prof. Falken 2011-06-03 22:56:07

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

@dwerner 2011-06-21 20:03:02

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

@Timmmm 2011-08-02 09:58:33

Isn'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.

@Gevorg 2011-08-12 01:31:43

Java 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!

@ubershmekel 2011-08-18 17:01:01

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

@Scott Stanchfield 2012-01-26 22:15:51

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

@Bill Rosmus 2012-05-08 16:02:07

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

@sergiofbsilva 2012-05-30 19:32:50

Think of methods params as local variables initialized with a value.

@pop stack 2012-06-03 09:17:04

@erlando, can we have a similar example of distinction for Array Objects?

@Scott Stanchfield 2012-08-30 04:44:34

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

@Bill Rosmus 2012-08-30 05:32:06

@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-30 05:54:16

@Scott Stanchfield and C was not strictly pass by value. Look at the pass by value and pass by reference links here:… 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.

@Steve Powell 2012-09-11 15:30:22

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

@Khaled.K 2013-03-24 14:18:13

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

@shakthi 2013-06-01 17:10:55

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) {"Max"); // true // d = *(new Dog("Fifi")); //<- C++ does not allows this //So what is point in in arguing passed by reference or not }

@Angelo 2013-06-08 07:53:57

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

@Mike Braun 2013-11-30 17:08:37

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

@Bill Rosmus 2013-12-09 01:38:31

@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?

@Mike Braun 2013-12-10 17:42:57

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

@Psyrus 2014-01-11 01:02:21

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

@seeker 2014-02-07 19:14:01

Shouldnt the first snippet follow the second one? Or am I seeing this the wrong way?

@John Strickler 2014-03-12 17:39:13

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

@Leonardo 2014-05-08 12:05:05

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

@orfdorf 2014-10-23 04:13:24

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

@ArtB 2014-11-27 16:53:08

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

@Shawn 2015-02-20 03:32:15

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

@Tito 2015-06-18 00:11:33

Só Java passes, by value, the reference to the object?

@DavidS 2015-08-04 21:22:29

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

@Impossibility 2015-08-19 23:47:35

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

@PC Luddite 2015-08-31 20:11:42

@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-31 20:20:50

Nobody has mentioned that C# does implement pass by reference with the use of the ref keyword.

@Revanth Kumar 2016-01-08 22:48:13

public class trial { static trial t_ = new trial(); public class trial1 { private String s = "hmm"; } public static void main(String[] args) { trial1 t = trial1(); foo(t); System.out.println("main: " + t.s); } private static void foo(trial1 t) { t = 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.

@Scott Stanchfield 2016-01-15 14:14:55

@RevanthKumar - Hard to tell from the formatting; I assume your special line is the "t = 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.

@Cdaragorn 2016-05-06 20:34:48

I'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.

@a better oliver 2016-05-09 13:24:06

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

@Cdaragorn 2016-05-12 15:31:29

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

@a better oliver 2016-05-13 06:47:28

@Cdaragorn "In your example (foo(&x)) ... Your passing a reference to x" Um, that's the point I was making.

@Cdaragorn 2016-05-16 20:42:29

Ok, 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.

@EpicPandaForce 2016-06-06 10:51:10

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

@Kai Wang 2016-10-25 18:58:44

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

@MC Emperor 2017-01-07 11:58:55

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.

@jayendra bhatt 2017-01-19 18:01:13

or we can say it is not pass by reference but it is object's reference passed by value.

@Smit 2017-03-07 10:03:53

I am Little confused. Can Anyone explain this concept of array being pass by reference?

@Jajikanth pydimarla 2017-03-21 16:24:44

During Compile time , java behaves as pass by reference.during runtime it's pass by value.

@peter 2017-04-01 17:39:44

Is it safe to say that Java uses semi references because modification mutates the original object?

@Aluan Haddad 2017-04-29 03:20:21

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

@Satyendra Kumar 2017-06-24 16:09:26

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

@Kos 2017-07-06 12:22:09

Long story short, the problem is using the same word for "reference to an object" vs. "reference to a variable"

@aioobe 2017-07-20 00:11:33

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

@Aaron 2017-08-02 14:58:09

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

@Nicolas C 2017-08-24 13:48:01

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.

@Hiroki 2017-09-16 07:59:19

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

@RecursiveExceptionException 2017-10-17 00:07:46

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!

@morten 2017-10-26 08:53:40

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.

@Grigore Madalin 2017-11-12 08:00:27

All 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-12 08:01:34

The 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-12 08:08:41

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

@Bohao LI 2017-12-06 19:42:40

We can just treat the reference as an equivalence of pointer in c++.

@huangzonghao 2018-03-24 03:10:50

It seems that essentially java is pass-by-value for primitives and pass-by-reference for objects

@ikegami 2018-03-30 09:26:49

As 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-30 09:28:17

Re "What's confusing is that object references are actually pointers", Well yeah. References are pointers on which one can't do pointer arithmetic.

@Giacomo 2018-07-17 08:25:53

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 =;}, then after passing myHead to changeHead, its value has changed to 155, but the head is still the initial head and not . I somehow can not match this two examples to find a general rule.

@the hand of NOD 2018-08-01 12:38:08

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: [… (Application Classloading and Pass-by-Value or Reference)

@pathe.kiran 2018-08-18 18:34:21

erlando'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.

@spicypumpkin 2018-09-12 17:13:38

@SatyendraKumar This is an infuriatingly underrated comment. I got a good laugh.

@spicypumpkin 2018-09-12 17:18:10

@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-12 17:23:19

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

@Aaron 2018-09-13 15:42:01

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

@spicypumpkin 2018-09-13 16:04:06

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

@Aaron 2018-09-13 16:23:36

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

@spicypumpkin 2018-09-13 16:49:19

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

@Aaron 2018-09-13 17:11:04

@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'.

@hamza belmellouki 2018-09-14 02:29:18

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, even though the method can alter the object to which the caller's variable refers, it can not modify the variable itself.

In the example below, the println(sb_actual) call prints "Foo", not "Bar" because the assignment to sb_formal in addFoo() does not change the caller's sb_actual variable.

void addFoo(StringBuffer sb_formal) {
    sb_formal.append("Foo");           // Modifies the object created by the caller.
    sb_formal = new StringBuffer();    // Creates a new object.
    sb_formal.append("Bar");           // Modifies the new object.

void caller() {
    StringBuffer sb_actual = new StringBuffer();
    System.out.println(sb_actual);  // sb_actual still refers to the original object here.

@Martin B 2019-01-06 16:27:57

private void test1(String s) { s="h"; //Value is never used, since this is the same as changing the original object } private void test2(String[] s) { s[0]="h"; //contents inside the original object are changed s=new String[]{"k"}; //s is now just a local object s[0]="l"; //since the s object reference is passed by value, //ie. the original object reference ("pointer") or the object or structure itself cannot be changed }

@Felypp Oliveira 2018-02-02 21:23:56

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


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 assignment works. I found it in the docs :

One of the most common operators that you'll encounter is the simple assignment operator "=" [...] it assigns the value on its right to the operand on its left:

int cadence = 0;
int speed = 0;
int gear = 1;

This operator can also be used on objects to assign object references [...]

It's clear how this operator acts in two distinct ways: assign values and assign references. The last, when it's an object... the first, when it isn't an object, that is, when it's a primitive. But so, can we understand that Java's function params can be pass-by-value and pass-by-reference?

The truth is in the code. Let's try it:

public class AssignmentEvaluation
  static public class MyInteger
    public int value = 0;

  static public void main(String[] args)
    System.out.println("Assignment operator evaluation using two MyInteger objects named height and width\n");

    MyInteger height = new MyInteger();
    MyInteger width  = new MyInteger();

    System.out.println("[1] Assign distinct integers to height and width values");

    height.value = 9;
    width.value  = 1;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", we are different things! \n");

    System.out.println("[2] Assign to height's value the width's value");

    height.value = width.value;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", are we the same thing now? \n");

    System.out.println("[3] Assign to height's value an integer other than width's value");

    height.value = 9;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", we are different things yet! \n");

    System.out.println("[4] Assign to height the width object");

    height = width;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", are we the same thing now? \n");

    System.out.println("[5] Assign to height's value an integer other than width's value");

    height.value = 9;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", we are the same thing now! \n");

    System.out.println("[6] Assign to height a new MyInteger and an integer other than width's value");

    height = new MyInteger();
    height.value = 1;

    System.out.println("->  height is " + height.value + " and width is " + width.value + ", we are different things again! \n");

This is the output of my run:

Assignment operator evaluation using two MyInteger objects named height and width

[1] Assign distinct integers to height and width values
->  height is 9 and width is 1, we are different things! 

[2] Assign to height's value the width's value
->  height is 1 and width is 1, are we the same thing now? 

[3] Assign to height's value an integer other than width's value
->  height is 9 and width is 1, we are different things yet! 

[4] Assign to height the width object
->  height is 1 and width is 1, are we the same thing now? 

[5] Assign to height's value an integer other than width's value
->  height is 9 and width is 9, we are the same thing now! 

[6] Assign to height a new MyInteger and an integer other than width's value
->  height is 1 and width is 9, we are different things again! 

In [2] we have distinct objects and assign one variable's value to the other. But after assigning a new value in [3] the objects had different values, which means that in [2] the assigned value was a copy of the primitive variable, usually called pass-by-value, otherwise, the values printed in [3] should be the same.

In [4] we still have distinct objects and assign one object to the other. And after assigning a new value in [5] the objects had the same values, which means that in [4] the assigned object was not a copy of the other, which should be called pass-by-reference. But, if we look carefully in [6], we can't be so sure that no copy was done... ?????

We can't be so sure because in [6] the objects were the same, then we assigned a new object to one of them, and after, the objects had different values! How can they be distinct now if they were the same? They should be the same here too! ?????

We'll need to remember the docs to understand what's going on:

This operator can also be used on objects to assign object references

So our two variables were storing references... our variables had the same reference after [4] and different references after [6]... if such a thing is possible, this means that assignment of objects is done by copy of the object's reference, otherwise, if it was not a copy of reference, the printed value of the variables in [6] should be the same. So objects (references), just like primitives, are copied to variables through assignment, what people usually call pass-by-value. That's the only pass-by- in Java.

@asok 2018-05-17 12:41:46

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 " +;
        System.out.println("after change " +;


before change 50
after add 600
after change 50

@SnobOfTheGolfClub 2018-10-07 17:26:14

Please clarify that primitives are pass by value, whereas objects are passed by reference. Consider a method like: void changeName(Person person, String newName){ = newName; } which does indeed modify the original object. If this was truly pass-by-value, wouldn't we expect the given person argument to be a copy of the original object?

@Michael 2018-10-29 11:45:09

@SnobOfTheGolfClub objects are still passed by value even though operations on them behave like pass-by-reference. Consider void changePerson(Person person){ person = new Person(); } the callers reference to the person object will remain unchanged. Objects themselves are passed by value but their members can be affected by changes. To be true pass-by-reference, we would have to be able to reassign the argument to a new object and have the change be reflected in the caller.

@Himanshu arora 2017-04-08 05:51:29

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

@CodeKiller 2018-08-28 14:48:08

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.i = 2;
        h.b = true;
        System.out.println(h.s + " " + h.i + " " + h.b);

        System.out.println(h.s + " " + h.i + " " + h.b);

        String test = "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.

@georgeawg 2018-07-25 15:40:46

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?

@Dennis 2018-08-25 21:08:34

I'm not sure it's technically correct to mention that copies are made for primitive types. Primitive types are immutable which is why they cannot be modified inside a method they are passed to. The difference is negligible for things like numbers, but there is an important difference for potentially large strings.

@Torben 2018-10-03 04:40:21

This answer is completely incorrect and only creates confusion. Java is a pure pass-by-value language. What confuses you is that the value can be a pointer to an object. Pass-by-reference means one would be able to change the identity of an object at the caller's side. E.g. assigning a new object to a method parameter would also affect the pointer that was passed in the code that called the method.

@nasch 2018-12-27 18:49:38

@Dennis Strings are not primitives, they're objects.

@Hank Gay 2008-09-02 20:21:04

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!";

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.

@MaxZoom 2015-02-11 05:36:27

I would rather say that bar is a copy of the reference baz (or baz alias), that points initially to the same object.

@Mehdi Karamosly 2018-12-10 21:53:15

isn't there a slight different between String class and all other classes ?

@madcobra 2018-04-03 23:48:10

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



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.

@Ganesh 2013-10-17 07:54:30

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(); = "initialvalue";
        new PassByValue().changeValue(t);

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

class Test {
    String name;

The output of this program is:


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(); = "initialvalue";
        new PassByValue().changeRefence(t);

    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.

@mc01 2018-03-16 23:25:34

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

@Christophe Roussy 2018-02-20 10:26:08

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.

    ArrayList<Integer> list2 = new ArrayList<>(); // Another object.

    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;
    x = 21;

@JacquesB 2009-01-12 20:50:25

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.

@Prof. Falken 2011-02-09 09:50:58

Colloquially called a pointer.

@Hot Licks 2013-09-22 14:09:21

@Gevorg - Then what is a "NullPointerException"?

@JacquesB 2013-09-23 14:08:10

@Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException.

@Hot Licks 2013-09-23 15:46:14

It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding.

@moronkreacionz 2015-12-29 21:36:08

I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity.

@cutmancometh 2013-09-11 11:34:30

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;

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

@Brian Peterson 2013-11-01 06:53:33

However, you should have followed up with a more complex example where a function appears to alter a variable to whose address it has a reference.

@cHao 2013-12-18 04:48:00

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

@cutmancometh 2013-12-18 09:19:14

That'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-18 09:22:57

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

@cHao 2013-12-18 14:38:19

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

@cHao 2013-12-18 14:55:10

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

@fishinear 2014-03-02 15:37:40

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

@Aluan Haddad 2016-04-24 14:13:06

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

@Dawood ibn Kareem 2017-01-25 10:05:10

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

@cutmancometh 2017-01-25 18:14:16

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-25 18:31:46

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.

@Faraz Durrani 2017-03-25 20:37:09

@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-25 20:38:02

if not in this answer then somewhere. Please explain to me why swap method fails!

@cutmancometh 2017-04-03 13:37:38

Sure, can you be more specific? Could post post the code you're referring to in, or even just There's plenty of room for abiguity in the term "swap method", and I'd hate to give you incomplete information.

@Aluan Haddad 2017-04-29 03:33:00

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

@Gevorg 2011-08-12 01:22:19

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);
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!

@dpp 2012-02-25 03:29:07

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

@Gevorg 2012-02-25 21:25:22

@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! ;)

@dpp 2012-02-28 03:16:43

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.

@Ahmed 2012-07-05 07:27:27

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?

@Geronimo 2012-08-02 04:51:11

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

@curious 2012-11-12 11:01:09

one reason can be that java does not allow you to change that address so it gives you a copy of the reference(security)

@DaveM 2013-06-07 09:09:02

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.

@Aquarelle 2014-01-18 23:15:36

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-18 23:23:10

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.

@John Strickler 2014-03-12 17:38:45

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

@brain storm 2014-08-20 17:42:17

I guess Java designed with pointers in mind. Otherwise, why NullPointerException exists? Nevertheless, for this wonderful explanantion, getting pointers will just make it complicated

@TheBrenny 2014-10-19 12:20:23

So drop in on theoretical line #9 System.out.println(person.getName()); what will show up? "Tom" or "Jerry"? This is the last thing that will help me hurdle this confusion.

@Erick G. Hagstrom 2015-08-30 16:54:27

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.

@z33k 2018-02-25 11:58:06

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.

@killjoy 2018-05-02 13:19:12

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 !

@Raj S. Rusia 2017-09-06 14:13:22

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

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

        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;

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.

@Premraj 2017-12-16 10:19:10

  • 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
        System.out.println(i);  //prints 5

    private static void change(int i) {
        System.out.println(i);  //prints 5
        System.out.println(i); //prints 10


Example using object:

public class PassByValueObject {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        new PassByValueObject().change(list);
        System.out.println(list); // prints [prem, raj, ram]


    private  void change(List list) {
        System.out.println(list.get(0)); // prem
        System.out.println(list.add("bheem")); //gets NullPointerException

@NAGHMAAN MOHASEEN 2017-10-22 07:08:44

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

@Learner 2017-11-18 07:53:57

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.

@user1767316 2016-07-24 08:29:59

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.

@Mox 2017-01-18 11:40:26

So it's byRef in regards to objects and byVal in regards to primitives?

@user1767316 2017-01-25 23:28:13

@mox please read: Objects are not passed by reference, this is a ledgend: String a=new String("unchanged");

@user1767316 2017-01-25 23:35:22

public void changeit(String changeit){changit = "changed";} changeIt(a); assert(a.equals("unchanged"));

@Aaron 2017-08-02 15:07:10

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

@philipxy 2017-09-27 08:36:50

@Aaron "Pass by reference" does not mean "pass a value that is a member of a type that is called a 'reference' in Java". The two uses of "reference" mean different things.

@Aaron 2017-09-27 13:55:50

@philipxy Because of some very arbitrary decision that has been made by a sub-set of the software community. What you describe is an opinion of how "Pass by reference" works, not a universally accepted definition. Even if you cite a few computer science books which agree with you, that only means that those authors share your opinion. English is English, and no matter how much the "pass by reference definition purists" want to argue the point they are merely arguing semantics about a non-universal opinion. Some of the answers here are nit-picky about the subjective definition of a nit.

@zakmck 2017-10-30 08:40:51

Quite confusing answer. The reason why you can't change a string object in a method, which is passed by reference, is that String objects are immutable by design and you can't do things like strParam.setChar ( i, newValue ). That said, strings, as anything else, are passed by value and, since String is a non-primitive type, that value is a reference to the thing that was created with new, and you can check this by using String.intern().

@zakmck 2017-10-30 08:45:42

Instead, You can't change a string via param = "another string" (equivalent to new String ( "another string" ) ) because the reference value of param (which now points to "another string") cannot come back from the method's body. But that's true for any other object, the difference is that, when the class interface allows for it, you can do param.changeMe() and the top level object being referred will change because param is pointing at it, despite param's reference value itself (the addressed location, in C terms) cannot pop up back from the method.

@Khaled.K 2013-06-02 05:30:44

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

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

@user207421 2017-09-17 10:09:47

'Pass its inner value' is meaningless.

@Khaled.K 2017-09-17 16:41:46

@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

@user6091735 2017-11-18 16:26:37

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

@Supriya 2017-09-03 18:52:48

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
    int a = 5;
    System.out.println("Three: " + a);    //5

    DummyObject dummyObject = new DummyObject();
    System.out.println("One: " + dummyObject.getObj());    //555
    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();
    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 ( can help gain a deeper understanding.

@Flyout 2017-10-16 15:18:26

First you said - "Java is pass by value" and then you said - "[...] otherwise, the change is reflected as the modifications are only made on a "reference" of the object" = Java is passed by reference

@Gaurav 2013-07-10 06:31:27

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

public void test() {
    MyClass obj = null;
    //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();

@David Schwartz 2017-06-10 23:24:59

This is the clearest, simplest way to see that Java passes by value. The value of obj (null) was passed to init, not a reference to obj.

@Basheer AL-MOMANI 2017-03-30 09:29:06

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

@Michał Żbikowski 2014-09-25 00:23:38

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);
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){
  System.out.println("In Function: " + inFunction[0]);

int[] arOriginal = {10, 20, 30};
System.out.println("Original before: " + arOriginal[0]);
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);

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
  2. REF 2 Professor Mehran Sahami
  3. REF 3 c4learn

@Shailendra Singh 2016-07-08 15:26:49

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.

@David Schwartz 2017-06-10 23:27:00

@ShailendraSingh Java never passes by reference, period. See Gaurav's answer for a clear proof of this.

@Tom Blodget 2017-10-23 23:04:38

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

@Christian 2015-03-18 21:35:08

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!

@sakhunzai 2017-03-30 05:41:44

I think you nailed it by saying you can't change the reference from the object itself

@sakhunzai 2017-03-30 06:00:56

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

@Raja 2017-01-27 19:51:47

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);
        System.out.println("With the owner again:)");
        System.out.println("With the owner again(:");

    public static void goodVet (Dog dog) {
        System.out.println("At the good vet:");
        dog = new Dog(12); // create a clone
        dog.cutTail(6);    // cut the clone's tail

    public static void badVet (Dog dog) {
        System.out.println("At the bad vet:");
        dog.cutTail(2);   // cut the original dog's tail

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

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

@Rahul Kumar 2016-12-30 08:33:00

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:

public void sampleTest(){
    int i = 5;
    System.out.println("passed ==> "+ i);
    Integer j = new Integer(5);
    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:

public void sampleTest2(){
    Person person = new Person(24, "John");

 * @param person
private void alterPerson(Person person) {
    Person altered = person;

private static class Person{
    private int age;
    private String name; 

    public Person(int age, String name) {
        this.age=age; =name;

    public int getAge() {
        return age;

    public void setAge(int age) {
        this.age = age;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("Person [age=");
        builder.append(", name=");
        return builder.toString();


In this case, the output is:

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

@Taleev Aalam 2016-11-16 11:58:41

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


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


    public class Sample{
    public static void main(String args[]){
    S s=new S();
    S t=new S();








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( 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

Related Questions

Sponsored Content

40 Answered Questions

[SOLVED] How do I convert a String to an int in Java?

53 Answered Questions

[SOLVED] Creating a memory leak with Java

24 Answered Questions

[SOLVED] How to get an enum value from a string value in Java?

  • 2009-03-02 22:56:34
  • Malachi
  • 927423 View
  • 1720 Score
  • 24 Answer
  • Tags:   java enums

62 Answered Questions

[SOLVED] How do I generate random integers within a specific range in Java?

  • 2008-12-12 18:20:57
  • user42155
  • 3655220 View
  • 3087 Score
  • 62 Answer
  • Tags:   java random integer

15 Answered Questions

14 Answered Questions

[SOLVED] Passing a String by Reference in Java?

29 Answered Questions

[SOLVED] Is JavaScript a pass-by-reference or pass-by-value language?

19 Answered Questions

[SOLVED] Does Java support default parameter values?

23 Answered Questions

[SOLVED] How do I pass a variable by reference?

4 Answered Questions

[SOLVED] Javascript by reference vs. by value

Sponsored Content