I always thought Java was pass-by-reference; however I've seen a couple of blog posts (For example, this blog) that claim it's not. I don't think I understand the distinction they're making.

What is the explanation?

507 upvote
  flag
I believe that much of the confusion on this issue has to do with the fact that different people have different definitions of the term "reference". People coming from a C++ background assume that "reference" must mean what it meant in C++, people from a C background assume "reference" must be the same as "pointer" in their language, and so on. Whether it's correct to say that Java passes by reference really depends on what's meant by "reference". – Gravity
87 upvote
  flag
I try to consistently use the terminology found at the Evaluation Strategy article. It should be noted that, even though the article points out the terms vary greatly by community, it stresses that the semantics for call-by-value and call-by-reference differ in a very crucial way. (Personally I prefer to use call-by-object-sharing these days over call-by-value[-of-the-reference], as this describes the semantics at a high-level and does not create a conflict with call-by-value, which is the underlying implementation.) – user166390
upvote
  flag
upvote
  flag
There is a very good answer by pgras in this thread: //allinonescript.com/questions/589919/… – mark
upvote
  flag
Of course Java passes all the objects by reference! For the blog mentioned in the question, the foo(Dog d) is just creating a new object and making d pointing to the new address (d originally referred to the object which is also referred by aDog -- This is so-called "pass-by-reference"). It is changing the pointer, the original object is still in its place without any change. The point is there is no copy of the value of object at all, it only copies the reference value. – shuangwhywhy
1 upvote
  flag
And you cannot say it is "pass-by-value" just because the method doesn't change the pass-in value, you must check is any VALUE COPY there. – shuangwhywhy
40 upvote
  flag
@Gravity: Can you go and put your comment on a HUGE billboard or something? That's the whole issue in a nutshell. And it shows that this whole thing is semantics. If we don't agree on the base definition of a reference, then we won't agree on the answer to this question :) – MadConan
18 upvote
  flag
I would rather ask if values passed to methods are copied at time of invocation. I guess that this is the question you are looking for. – spectre
19 upvote
  flag
I think the confusion is "pass by reference" versus "reference semantics". Java is pass-by-value with reference semantics. – spraff
3 upvote
  flag
I usually use the term pass-by-pointer. Sure, the pointer is passed by value, but, after all, the pointer isn't what anyone cares about. This makes it clear that the pointer (not the object) is being copied, that mutating the pointed object will be visible to the caller, and that changing what the copy is pointing at will not be. – Kevin
upvote
  flag
a lot of the answers here are wrong or misleading. we should just forget the semantics and demonstrate the properties of a particular language with examples. – Alexander Mills
upvote
  flag
Java is focused towards code maintainability so they didn't include featuers that made code harder to maintain. For the most part these features allwed people to hand-optimize code where the compiler couldn't, but the Java runtime allows an alternative so that featuers like free pointers and references just don't give that much of a performance boost to make them worth the destabilizing effect. C/C++ offer a different path--you don't have to trust a runtime and have more control over the hardware. Both are valid, but pass by ref and pointers would be really bad ideas in java. – Bill K
upvote
  flag
If java is "pass by value" then why the result of below program is : //0 //1 //2 ( may be you are using "String" which is an immutable class ) public class Newfile{ public int x=0; }public class HelloWorld{ public static void changeX(Newfile tr){ tr.x++; } public static void main(String []args){ Newfile trf = new Newfile(); System.out.println(trf.x); changeX(trf); System.out.println(trf.x); changeX(trf); System.out.println(trf.x); } } – Anand M Arora
7 upvote
  flag
@Gravity, while you're absolutely correct in that folks coming from C++ will instinctively have a different intuition set regarding the term "reference", I personally believe the body is more buried in the "by". "Pass by" is confusing in that it is absolutely distinct from "Passing a" in Java. In C++, however it colloquially is not. In C++ you can say "passing a reference", and it's understood that it will pass the swap(x,y) test. – user4229245
2 upvote
  flag
@anandmarora, in your example, the changeX() method is taking a reference as a parameter. That reference is passed to it as a value. Consider what would happen if your method was instead defined like this: void changeX(Newfile tr){ tr = new Newfile();} If java were PBR, then the method calling changeX() would have it's object switched out entirely. Because it is PBV, the nothing happens after changeX() returns. – user4229245
upvote
  flag
Never understood the confusion about the Java pass-by-eference vs. pass-by-value confusion (c/ c++ background, now a c#-programmer). Calling a Methode with a pointer passes the pointer and allows you to change the underlying object. Passing a pointer to a pointer allows you to change the original pointer to an object. Java have no concept of "pointer of pointers" and that's it. (C++-references are just obscufacted pointers) – Peter Schneider
2 upvote
  flag
Some concepts are just a bit difficult, and we are not helped by languages trying to make them "safe" or to "hide" them. This Question has over 3/4 of a MILLION Views and 55 Answers... The real answer should be: "Draw a diagram for yourself and keep looking at it until you understand." There are much harder issues than this, and if you can't get it fairly easily, it does not bode well for you as a programmer. – user4624979
3 upvote
  flag
The Java Language Specification defines a "reference" as a pointer. Also, the definitions of "call by value" and "call by reference" in computer science are not ambiguous. "Call by value" means that changes to an argument in the method are not visible to the caller; "call by reference" means that they are not. The stuff about "it depends on how you define 'reference'" is irrelevant and inapplicable. Java method calls are unambiguously call by value. – Lew Bloch
4 upvote
  flag
1. Java is pass-by-value. 2. For primitives, you pass a copy of the actual value. 3. For references to objects, you pass a copy of the reference (the remote control). javaranch.com/campfire/StoryPassBy.jsp – Max
upvote
  flag
Oracle should really make a page for that and make things clear – OverCoder
1 upvote
  flag
Look at the next answer, which really answers the question: Java does BY-VALUE. Period. – Michael
upvote
  flag
It's pass-by-value. So Java will COPY an object that you hand as a parameter. But, the references to object (memory addresses) inside that object are values, so are copied and still point to the same memory. So, if you change a referenced object contained INSIDE of an object that you handed as a parameter, it will change the memory and thus the original object. Whereas if you just change the object handed as a parameter, the original object is unchanged. Primitives (ints, floats, arrays, etc) are copied as values and don't have this style of references. – Araymer
upvote
  flag
How did you assume pass-by-reference ? – Manish Shrivastava
upvote
  flag
As a pure Java programmer, reference is not confusing, but pass by is. What is pass-by? – FaithReaper
upvote
  flag
Java always pass arguments by value, the copy would be either a reference or a variable depending on the actual variable type. Check out this article to find a practical example and tips programmergate.com/java-pass-reference-pass-value – Hussein Terek
1 upvote
  flag
java is reference based and mostly it acts call by reference. – A.Shaheri

73 Answers 11

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

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

So, when calling a method

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

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

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

6 upvote
  flag
Since the values of the primitives are immutable (like String), the difference between the two cases is not really relevant. – Paŭlo Ebermann
4 upvote
  flag
Exactly. For all you can tell via observable JVM behavior, primitives could be being passed by reference and could live on the heap. They don't, but that's not actually observable in any way. – Gravity
5 upvote
  flag
primitives are immutable? is that new in Java 7? – Carlos Heuberger
upvote
  flag
2 upvote
  flag
@CarlosHeuberger, "primitives are immutable?". The point is that you can pretend that 'primitives' are actually (mutable) references to immutable objects. – Aaron McDaid
3 upvote
  flag
Pointers are immutable, primitives in general are mutable. String is also not a primitive, it is an object. Moreover, the underlying structure of the String is a mutable array. The only immutable thing about it is the length, that being the inherent nature of arrays. – kingfrito_5005
upvote
  flag
This is another answer pointing out the largely semantic nature of the argument. The definition of reference provided in this answer would make Java "pass-by-reference." The author essentially admits as much in the last paragraph by stating that it is "indistinguishable in practice" from "pass-by-reference." I doubt OP is asking because of a desire to understand the Java implementation but rather to understand how to correctly use Java. If it were indistinguishable in practice, then there would be no point in caring and even thinking about it would be a waste of time. – Aaron
upvote
  flag
How is this answer correct? The very concept of "pass-by-value", just like "value types", implies your are dealing with data that lives directly in variables and is thus copied on assignment. Just because Java doesn't provide access to raw pointers doesn't matter: Objects act fundamentally different to primitive data types. They are not both pass-by-value – RecursiveExceptionException

Java passes references by value.

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

22 upvote
  flag
But the thing that keeps getting repeated "you can't change the value of objects passed in arguments" is clearly false. You may not be able to make them refer to a different object, but you can change their contents by calling their methods. IMO this means you lose all the benefits of references, and gain no additional guarantees. – Timmmm
27 upvote
  flag
I never said "you can't change the value of objects passed in arguments". I will say "You can't change the value of the object reference passed in as a method argument", which is a true statement about the Java language. Obviously you can change the state of the object (as long as it's not immutable). – ScArcher2
upvote
  flag
I wasn't disagreeing with you. Sorry if that wasn't clear! – Timmmm
15 upvote
  flag
Keep in mind that you cannot actually pass objects in java; the objects stay on the heap. Pointers to the objects can be passed (which get copied onto the stack frame for the called method). So you never change the passed-in value (the pointer), but you're free to follow it and change the thing on the heap to which it points. That's pass-by-value. – Scott Stanchfield
upvote
  flag
Java passes references by value. You can change data at the memory the reference points to. In the method you can change the reference variable, but after the function exits the reference is reverted back (but not the memory this reference is pointing at). – Willmore
3 upvote
  flag
Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument... – John Strickler
1 upvote
  flag
Java does not pass an object, it passes the value of the pointer to the object. This creates a new pointer to that memory location of the original object in a new variable. If you change the value (the memory address it points to) of this pointer variable in a method, then the original pointer used in the method caller remains unmodified. If you are calling the parameter a reference then the fact that it is a copy of the original reference, not the original reference itself such that there are now two references to the object means that it is pass-by-value – theferrit32
upvote
  flag
@theferrit32 This is straight up ridiculous. Obviously, at the lowest possible level, there will be values because without values there's nothing there. It's utterly stupid because you are presenting a fact not for whether Java is purely pass-by-value but rather for why the destinction between pass-by-value and pass-by-reference are meaningless. Again, without data there's no data, so obviously every pass-by-reference implementation will deal with data at some level. But abstracting the concept to such a degree is ridiculous. Why not call Java "transfer-by-entity" – RecursiveExceptionException
upvote
  flag
There is a difference though, because some languages do pass by reference, which is a different data type from a basic pointer, which is essentially what Java is using. Consider a reference to be just an abstraction level above a pointer. If you have a reference you can modify the value of the actual memory location used by the function caller. Java does not work this way though, it passes a new memory location containing the value of the object pointer, not a reference to the pointer. In Java you cannot modify the value passed from the caller into the function, in some languages you can. – theferrit32

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

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

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

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

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

Java passes references to objects by value.

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

It goes like this:

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

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

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

Likewise:

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

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

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

181 upvote
  flag
Isn't it slightly confusing the issue with internal details? There's no conceptual difference between 'passing a reference' and 'passing the value of a reference', assuming that you mean 'the value of the internal pointer to the object'. – izb
304 upvote
  flag
But there is a subtle difference. Look at the first example. If it was purely pass by reference, aDog.name would be "Fifi". It isn't - the reference you are getting is a value reference that if overwritten will be restored when exiting the function. – erlando
4 upvote
  flag
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. – Lorenzo Boccaccia
236 upvote
  flag
@Lorenzo: No, in Java everything is passed by value. Primitives are passed by value, and object references are passed by value. The objects themselves are never passed to a method, but the objects are always in the heap and only a reference to the object is passed to the method. – Esko Luontola
229 upvote
  flag
My attempt at a good way to visualize object passing: Imagine a balloon. Calling a fxn is like tieing a second string to the balloon and handing the line to the fxn. parameter = new Balloon() will cut that string and create a new balloon (but this has no effect on the original balloon). parameter.pop() will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed. – dhackner
2 upvote
  flag
Your point might be clearer if the name passed to the constructor was different than the name used in the foo method. – Ishmael
94 upvote
  flag
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
3 upvote
  flag
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: java.sun.com/docs/books/jls/third_edition/html/… – Prof. Falken
1 upvote
  flag
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. – dwerner
11 upvote
  flag
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. – Timmmm
7 upvote
  flag
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! – Gevorg
5 upvote
  flag
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". – ubershmekel
16 upvote
  flag
@ubershmekel - no, that's not correct. "Passing references by value" in Java is exactly the same as "passing a pointer by value" in C++. Passing by reference in C++ allows the called function/method to actually change the variable used to pass the value. Passing by value always allows the called function/method to read-and-follow a pointer passed by value... – Scott Stanchfield
15 upvote
  flag
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. – BillR
upvote
  flag
Think of methods params as local variables initialized with a value. – sergiofbsilva
upvote
  flag
@erlando, can we have a similar example of distinction for Array Objects? – pop stack
11 upvote
  flag
@BillR - C was strictly pass-by-value; C++ added pass-by-reference semantics, but by no means was it the first language to implement those semantics. The term "pass-by-reference" has a very specific meaning, and Java simply does not implement it. Keep the terms simple and to what they actually mean and its much easier to understand and explain. Java passes everything by value, including pointers. (It's also easiest if you simply avoid using the term "reference" at all in Java... they're pointers...) – Scott Stanchfield
6 upvote
  flag
@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. – BillR
3 upvote
  flag
@Scott Stanchfield and C was not strictly pass by value. Look at the pass by value and pass by reference links here: publib.boulder.ibm.com/infocenter/comphelp/v8v101/… 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. – BillR
4 upvote
  flag
@BillR Not so. Java is pass by (new L)value. The terms pass by reference/(new L)value/macro are terms defined (for example) by the Scott-Strachey theory of programming languages and Java is definitely passing by (new L)value. Your little test example didn't update the caller's variable but instead probably updated the object referenced by the caller's variable. – Steve Powell
upvote
  flag
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 .. – Khaled.K
upvote
  flag
Really its a dilemma in the terminology. Consider the same example in terms of c++, for which everybody hopefully agree its 'passed by reference' (or its reference passed by value?) void foo(Dog & d) { d.name.equals("Max"); // true // d = *(new Dog("Fifi")); //<- C++ does not allows this //So what is point in in arguing passed by reference or not } – shakthi
1 upvote
  flag
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. – Angelo
5 upvote
  flag
@BillR Incredible that despite the utterly clear answer you're still arguing against it. Java passes only pointers. A pointer is an opaque type that we can think of as being a primitive number. This number is passed by value. So Java passes pointers, and those pointers are pass by value. – Mike Braun
3 upvote
  flag
@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? – BillR
34 upvote
  flag
@BillR I have a comp. sci master and learned programming in C and C++. I've build compilers and CPU emulators. I think I have a fair grasp of both language theory and low level system dynamics. I can without a shadow of doubt say that you are wrong. Passing a pointer is NOT pass by reference. The pointer itself is a numeric that you can pass either by value or by reference. In C++ you can do both. In Java you can only pass by value. It has been shown to you that you can't change the variable holding the pointer. You can only follow the pointer, but that does not change the calling method. – Mike Braun
5 upvote
  flag
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. – Psyrus
upvote
  flag
Shouldnt the first snippet follow the second one? Or am I seeing this the wrong way? – KodeSeeker
4 upvote
  flag
Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument... – John Strickler
3 upvote
  flag
@JohnStrickler I have seen a recent example of my colleague 'nulling' the object arguments at the end of the invoked method, and expecting to see it 'nulled' in the caller. So, you are quite right that it may be 'purism', but many people still ignore it (and still they produce lines of code). – Leonardo
2 upvote
  flag
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. – orfdorf
upvote
  flag
@erlando I tried to update the answer to reflect your comment. Please review, I don't want to mislead people on such a question. :) – ArtB
1 upvote
  flag
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. – Shawn
3 upvote
  flag
Só Java passes, by value, the reference to the object? – Tito
3 upvote
  flag
@BillR: "Java modifies the meaning of 'pass by reference' from languages like C/C++..." and there is the root of your misunderstanding. Java doesn't get to "modify the meaning of 'pass by reference'" any more than I do. The term already has a meaning in computer science. It's useless and confusing to try to persuade people that "pass by reference" has different meanings in different languages. – DavidS
1 upvote
  flag
@BillR Pass by reference: void f(std::string & s) { s = std::string("A different string."); } Pass pointer by value: void f(std::string * s) { s = new std::string("A different string."); } If you take the address of a string and pass it to the second function, you aren't changing the original, but if you pass it by reference to the first, you are. – Impossibility
5 upvote
  flag
@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
1 upvote
  flag
Nobody has mentioned that C# does implement pass by reference with the use of the ref keyword. – PC Luddite
upvote
  flag
public class trial { static trial t_ = new trial(); public class trial1 { private String s = "hmm"; } public static void main(String[] args) { trial1 t = t_.new trial1(); foo(t); System.out.println("main: " + t.s); } private static void foo(trial1 t) { t = t_.new trial1(); //special line t.s = "noo"; System.out.println("foo: " + t.s); } } If i remove the line tagged as special line, both the syso's are returning the updated value. Does that mean we are sending a pointer of the trial1 object to foo? Please use a formater to look at the code. – Revanth Kumar
upvote
  flag
@RevanthKumar - Hard to tell from the formatting; I assume your special line is the "t = t_.new trial1()" line? If so, then yes. You have a pointer passed to foo. If the special line is run, the parameter t is changed to point to a new trial object, and the string in that new trial1 is changed. If that line is removed, foo follows the pointer to the trial1 passed in and changes its string. – Scott Stanchfield
1 upvote
  flag
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. – Cdaragorn
upvote
  flag
@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. – zeroflagL
1 upvote
  flag
@zeroflagL That's the problem. It is impossible to ever pass the variable itself. In your example (foo(&x)), you aren't passing x. Your passing a reference to x. By that definition, there is no such thing as pass by reference because it can never be done. – Cdaragorn
upvote
  flag
@Cdaragorn "In your example (foo(&x)) ... Your passing a reference to x" Um, that's the point I was making. – zeroflagL
1 upvote
  flag
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. – Cdaragorn
2 upvote
  flag
@izb the fact that pointers to objects are copied is different from the notion that objects are passed by reference. Because they are not passed by reference, their reference is copied. – EpicPandaForce
1 upvote
  flag
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. – Kai Wang
upvote
  flag
I would suggest to avoid using those terms altogether within a Java context. Just known how it really works in Java — this example did a great job doing so. – MC Emperor
upvote
  flag
or we can say it is not pass by reference but it is object's reference passed by value. – jayendra bhatt
upvote
  flag
I am Little confused. Can Anyone explain this concept of array being pass by reference? gist.github.com/shah-smit/0506d70f7a48b70eeddbe00b59ce6a84 – Smit
upvote
  flag
During Compile time , java behaves as pass by reference.during runtime it's pass by value. – Jajikanth
1 upvote
  flag
Is it safe to say that Java uses semi references because modification mutates the original object? – peter
upvote
  flag
@peter no, that is not correct. That is passing a copy of a pointer to a selectively mutable memory location. Mutating the value stored there is a side effecting operation that is observable to both the caller and the callee. – Aluan Haddad
1 upvote
  flag
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. – Satyendra Kumar
1 upvote
  flag
Long story short, the problem is using the same word for "reference to an object" vs. "reference to a variable" – Kos
1 upvote
  flag
@Shawn, I think you'd agree that Java is pass-by-value if you consider a Java Dog implicitly corresponding to a C++ Dog *. It makes sense if you consider the fact that all all initializations have new in it, like so: Dog d = new Dog(); A variable in Java can never hold an object. – aioobe
1 upvote
  flag
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) – Aaron
upvote
  flag
Great explanation!!! I would add that in case of Java RMI calls, the method receives a full serialized copy of the parameter, not the value of the reference. – Nicolas C
1 upvote
  flag
"When we pass the value of an object, we are passing the reference to it." Then, Java is a pass-by-reference language, I think... – Hiroki
upvote
  flag
Then why even have the two god damn terms? Yes, pass-by-reference will deal with values at some level but you don't have to abstract concepts to the n-th degree! – RecursiveExceptionException
upvote
  flag
I would say that, since Java is claiming to be Object Oriented, it is objects people care about, and objects people are interested in passing. The interesting thing most new developers in Java must realise, is that the only way to pass an object, is by passing a copy of the reference, giving pass by reference semantics for objects, which is what matters to 99% of people who ask this question. If the references themselves were passed by reference, it would be very confusing, and next to impossible to use the language. – morten
1 upvote
  flag
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
1 upvote
  flag
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
upvote
  flag
@erlando i really think in oder to improve your answer and make it complete you should mention this "reference" term meaning alteration that Java use. Unfortunately is very hard to teach Java programmers that they where told the wrong term. But this is the truth. At the end the winners write the history. Java rewrote the reference definition and people believe them simply because they win a lot of users. – Grigore Madalin
upvote
  flag
We can just treat the reference as an equivalence of pointer in c++. – Bohao LI
upvote
  flag
Isn't this just like how Python does it? – Solomon Ucko

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

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

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

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

upvote
  flag
I think it is very close to my understanding of Java object and its reference. Object in Java is passed to a method by a reference copy (or alias). – MaxZoom

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

2 upvote
  flag
I find your second-to-last sentence very misleading. It's not true that "all objects in Java are references". It's only the references to those objects that are references. – Dawood ibn Kareem

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

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

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

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

Prints:

Before: a = 2, b = 3
After: a = 2, b = 3

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

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

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

output of java PassByCopy:

name= Maxx
name= Fido

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

2 upvote
  flag
"pass by copy" is what pass-by-value means. – T.J. Crowder

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

Java is also mentioned. Here is the short summary:

  • Java passes it parameters by value
  • "by value" is the only way in java to pass a parameter to a method
  • using methods from the object given as parameter will alter the object as the references point to the original objects. (if that method itself alters some values)

I just noticed you referenced my article.

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

The key to understanding this is that something like

Dog myDog;

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

What that means, is when you have

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

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

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

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

if the Method were defined as

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

let's look at what's happening.

  • the parameter someDog is set to the value 42
  • at line "AAA"
    • someDog is followed to the Dog it points to (the Dog object at address 42)
    • that Dog (the one at address 42) is asked to change his name to Max
  • at line "BBB"
    • a new Dog is created. Let's say he's at address 74
    • we assign the parameter someDog to 74
  • at line "CCC"
    • someDog is followed to the Dog it points to (the Dog object at address 74)
    • that Dog (the one at address 74) is asked to change his name to Rowlf
  • then, we return

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

Did myDog change?

There's the key.

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

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

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

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

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

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

98 upvote
  flag
This is why the common refrain "Java doesn't have pointers" is so misleading. – Beska
119 upvote
  flag
You are wrong, imho. "Keeping in mind that myDog is a pointer, and not an actual Dog, the answer is NO. myDog still has the value 42; it's still pointing to the original Dog." myDog has value 42 but its name argument now contains "Max", rather than "Rover" on // AAA line. – Özgür
156 upvote
  flag
Think about it this way. Someone has the address of Ann Arbor, MI (my hometown, GO BLUE!) on a slip of paper called "annArborLocation". You copy it down on a piece of paper called "myDestination". You can drive to "myDestination" and plant a tree. You may have changed something about the city at that location, but it doesn't change the LAT/LON that was written on either paper. You can change the LAT/LON on "myDestination" but it doesn't change "annArborLocation". Does that help? – Scott Stanchfield
30 upvote
  flag
@Scott Stanchfield: I read your article about a year ago and it really helped clear things up for me. Thanks! May I humbly suggest a little addition: you should mention that there is actually a specific term that describes this form of "call by value where the value is a reference" that was invented by Barbara Liskov for describing the evaluation strategy of her CLU language in 1974, in order to avoid confusion such as the one your article addresses: call by sharing (sometimes called call by object-sharing or simply call by object), which pretty much perfectly describes the semantics. – Jörg W Mittag
3 upvote
  flag
I don't think we need another term. "Pass-by-value" covers this appropriately. Liskov rocks (I wonder if anyone ever said those exact words to her?), but "call by (object) sharing" adds nothing new. We could add a corresponding "Call by primitive" which also adds nothing new. I like to apply the KISS rule here... – Scott Stanchfield
2 upvote
  flag
Good article. I do not like to talk about pointers together with Java though.. When one knows how Java and its variables scope/lifetime work, reference is the term to use. With pointers people start wondering about pointing pointers or given that a reference is a pointer, about dereferencing a reference in a C++ fashion. That's not good. A variable is made of bits -a value-, and this value can reference an Object. That is, it tells the JVM how to find an Object in the Heap. This value is copied/duplicated and passed to a method variable that then can find the same object. No need for pointers. – Gevorg
upvote
  flag
So if the methood foo() returns someDog, and I use Dog rDog= foo(myDog), the rDog variable will be set to address 74 right? – rgamber
19 upvote
  flag
@Gevorg - The C/C++ languages don't own the concept of a "pointer". There are other languages that use pointers but do not allow the same types of manipulation of pointers that C/C++ allow. Java has pointers; they're just protected against mischief. – Scott Stanchfield
1 upvote
  flag
I totally agree with you; however in the book "Sun Certified Associate Study Guide - 2009 Ed", on page 183, question number 10 of the "Self Test Answers" of Chapter 5 says this: "Objects are always passed to methods by reference. This means changes made to the object in the method will be reflected in the object in the code that invoked the method." I agree with you, but what answer should I choose for this Java Test? – Juan I. Santa Cruz
4 upvote
  flag
Saying Java is pass by value is both meaningless and confusing. Everything on a computer is pass by value. In Java, when changing a passed-in array it changes the original array, so the array is not passed by value, it was passed by reference. The pointer was passed by value. It depends on the depth of abstraction and definition you use. In C++ when you change a pointer you are still accessing that pointer via a value, the memory location of it, but you would not call it pass by value. – Xonatron
upvote
  flag
It's very confusing to those of us who really want to understand what is going on to make blanket statements such as "Java is pass by value" when it clearly contains results that appear to be pass by reference. To use such low levels of abstraction on newcomers to the language is confusing, and ultimately meaningless when you go too far: as I said before, everything is pass by value on a computer at the lowest level. Now, please point out where I am wrong as in my confusion at the moment I could very well be wrong. – Xonatron
3 upvote
  flag
@Matthew - "Pass by value" has a very specific definition in programming language design. Not all parameters are passed by value; some languages (like C++ and Ada) do in fact pass parameters by reference (if you use the & [C++] or "in out" [Ada] modifier on the formal parameter definition). – Scott Stanchfield
upvote
  flag
@Matthew - Java does not, in fact, contain results that appear to be pass-by-reference. You cannot, from inside a method, change the value of a variable that was used as a parameter. (You can, of course, follow a pointer and change the contents of the object it points to, but that is not reference semantics; you're simply following a value). – Scott Stanchfield
1 upvote
  flag
@Matthew - Saying anything else to newcomers would be as incorrect as describing Java as a procedural language because they weren't familiar with object-oriented programming. If someone does not properly understand value vs. reference semantics, it's important to give them the proper understanding, especially if they later move to a language that does have reference semantics. (Imagine if you didn't understand it and assigned a parameter, like dog = new Dog(). In java, it doesn't change the external variable, but other languages might. Not knowing the difference causes confusion) – Scott Stanchfield
upvote
  flag
@Scott, following the pointer and changing the contents means the same thing as passing by reference at a higher level. An array can be considered its contents. It's a matter of language and definition. I understand how it works fundamentally. Java's problem is that it hides the fundamentals to begin with: joelonsoftware.com/articles/ThePerilsofJavaSchools.html. I agree 100% with your desire to have everyone understand what is actually happening, and maybe your "rocking the boat" causes people to pay attention. I'm just noting that it matters on the level of abstraction you dive to. – Xonatron
3 upvote
  flag
@Scott, I guess this better explains my point: If you see someone accepting Java as pass by reference, you can show a piece of code that breaks that theory. But, also, if you see someone accepting Java as pass by value, I can show code that breaks that theory, based on their weak higher level understanding of "pass by value". The terminology is at fault here. I think the best answer to this question would be to describe each of the "pass by" methods along with proper naming conventions that segregate them. – Xonatron
upvote
  flag
@ScottStanchfield, I referred to C++ because Java is its direct evolution. Regarding pointers, besides the NullPointerException there's nothing else left as you can see from the following White Paper java.sun.com/docs/white/langenv/Simple.doc2.html#4107 ! Also, even if I'm not an expert I believe that most JVMs use handles to objects and objects might be moved in the Heap while the reference value does not change (this shouldn't be happening in C/C++)! Still, I do not want to talk about JVMs implementation and I cannot believe that I just mentioned Java and 'Ps' in the same comment ;) – Gevorg
upvote
  flag
Good points but you are still essentially wrong in your conclusion. Java does pass by reference. Just because it has a reduced instruction set that doesn't allow you to change where the pointer points, doesn't make it pass by value. You are still maintaining a reference to the original object, you do not have a copy of the object so that the original is not changed. The only time this is not true is with immutable objects and primitives. This is like being politically correct or using propaganda... just because you say a turd is a steak doesn't mean it still doesn't taste like ... – BillR
upvote
  flag
@BillR - not at all like propaganda or being politically correct... Computer language design has very precise meanings for pass-by-value and pass-by-reference. If you cannot change the actual thing passed (the pointer to the Dog, in these examples) it's pass-by-value. By your logic, C has pass-by-reference semantics (which it more obviously does not) – Scott Stanchfield
upvote
  flag
@Scott Stanchfield Very good explanation. I will just add that when using RMI, references are managed separately so even if we update one instance in one side A (someDog.setName("NewName")) and then return immediately, it will not get updated in the other side B. I will explain it in detail later if I got the time. Regards. – Rodmar Conde
1 upvote
  flag
@RodmarConde - yep - check the "A Note on Remote Method Invocation (RMI)" section of my article: javadude.com/articles/passbyvalue.htm - the one that started this question. RMI calls have two modes: value and reference. – Scott Stanchfield
1 upvote
  flag
@Comptrol the pointer hasn't changed; its value is still 42. If it were pass-by-reference then it would change to the memory location of the new dog Fifi (which gets renamed to Rowlf, but the pointer wouldn't change a second time). Finally, if it were pass-by-reference, myDog would be called Rowlf after the method returned void. – Robert Grant
upvote
  flag
When you say, "...it's still pointing to the original Dog." is it because whatever happened in foo() was done to the value of the pointer pointing to myDog and once that method is done, then it's out of scope? From my understanding, if we're passing in a reference to "Rover", I don't understand why the operations inside foo() doesn't affect "Rover". – JPL
upvote
  flag
@JPL - in foo, line // AAA follows the pointer to the "Rover" dog and changes his name. line // BBB points the variable at a new dog, so anything else done with that variable doesn't affect the dog-formerly-known-as-Rover. After the method, myDog still points to the dog-formerly-known-as-Rover. – Scott Stanchfield
upvote
  flag
@ScottStanchfield I have always enjoyed this answer. I think that one thing which would really help, though, is if you had an addendum which dealt with a second method which accepted and reassigned a scalar. This is one of those topics I’ve taught a lot when dealing with JSSL (JS as a Second Language) devs. The dichotomy of modifying the contents of an object/list (which has side-effects out of scope, of course), versus reassigning the value of x in the outer scope, is the point where I find people go “aha!”. – Norguard
1 upvote
  flag
Of course the deeper answer as to why that’s proof of value passing (when the value of the complex object is clearly a reference, despite the scalar’s value being a copy of the scalar’s value) becomes less straightforward, but is hopefully an easier talk, thereafter. – Norguard
upvote
  flag
Hmmm... I guess I assumed that what happens with primitives was obvious... I hadn't thought about it. I could actually start the article with an example of passing in an int and then move to the Dog example to show it's doing the same thing. I really need to update it with some pictures that show the heap and stack, too... Thanks for the suggestion! – Scott Stanchfield
2 upvote
  flag
Looks like Java passes objects by a value of a reference to their value. – IllidanS4
upvote
  flag
One of the points in my article is that, what Gosling and Joy called "references" are pointers, from a programmer's point of view. (If it looks like a pointer and acts like a pointer, for all intents and purposes for the programmer, it's a pointer.) Their use of the term "reference" has caused all of the confusion over Java being pass-by-value. – Scott Stanchfield
upvote
  flag
So you're saying that in line // BBB of foo(), myDog (still at address 42) now points to the dog at address 74? And that the original dog (now named Max) is still located at address 42, but when 42 is read it points to address 74. So if you cannot retrieve Max (let's say he's a retriever to confuse things) how does he still exist. Can you still retrieve the retriever? (serious question) – YoungCoconutCode
upvote
  flag
Keep in mind that myDog is a pointer; it doesn't reside at 42 (it sits somewhere else in memory), it has value 42. When foo() is called, that 42 is passed in as parameter someDog. On // AAA we look at the value of someDog (42) and go to the Dog at 42 and change its name. On // BBB we change the value of someDog to 74. myDog (defined outside the method and still in scope) still has value 42. myDog is still active in the calling scope; you can access the Dog it points to (at 42 with name Fifi) outside foo(). You can no longer access that Dog inside foo() – Scott Stanchfield
upvote
  flag
So it's exactly like in C, but because pointers are hard, they removed the pointer operators in order to "make it easier"! – dividebyzero
1 upvote
  flag
@dividebyzero Not to make it easier, to make it more secure (as in, for example, not possible to walk off the end of an array). Even good C/C++ programmers have that happen. – Scott Stanchfield

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

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

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

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

In Java,

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

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

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

5 upvote
  flag
+1 I would also add Dog **objPtrPtr to the C++ example, that way we can modify what the pointer "points to". – Amro
upvote
  flag
This is one of the best answers I have seen so far. It mostly avoids the irrelevant semantics argument of "reference vs value of the reference" present elsewhere and instead discusses the mechanics of what actually happens. I had to give most other "pass-by-value" answers -1 because of their self-contradictory or factually false content, but this one gets +1 instead. – Aaron

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

The crux of the matter is that the word reference in the expression "pass by reference" means something completely different from the usual mening 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 someting completely different.

7 upvote
  flag
Colloquially called a pointer. – Prof. Falken
4 upvote
  flag
@Gevorg - Then what is a "NullPointerException"? – Hot Licks
1 upvote
  flag
@Hot: A unfortunately named exception from before Java settled on a clear terminology. The semantically equivalent exception in c# is called NullReferenceException. – JacquesB
3 upvote
  flag
It's always seemed to me that the use of "reference" in Java terminology is an affectation that hinders understanding. – Hot Licks
upvote
  flag
I learnt to call these so called "pointers to objects" as an "handle to the object". This reduced ambiguity. – moronkreacionz

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

class StringWrapper {
    public String value;

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

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

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

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

upvote
  flag
+1 for the swap test -- probably the most straightforward and relatable way to distinguish between passing by reference and passing a reference by value. Iff you can easily write a function swap(a, b) that (1) swaps a and b from the caller's POV, (2) is type-agnostic to the extent that static typing allows (meaning using it with another type requires nothing more than changing the declared types of a and b), and (3) doesn't require the caller to explicitly pass a pointer or name, then the language supports passing by reference. – cHao
upvote
  flag
"..for primitive datatypes you will work with an copy and for objects you will work with an copy of the reference to the objects" - perfectly written! – Raúl

A few corrections to some posts.

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

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

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

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

1 upvote
  flag
+1. What C does support, is treating references (which C calls pointers) as first-class values, and then passing them by value. – Jörg W Mittag
1 upvote
  flag
Yeah, in C you can create pointers not only on objects, but on arbitrary variables - so you can easily simulate "call-by-reference" of any variable. In Java this works only for variables which have a surrounding object, which you can give. – Paŭlo Ebermann

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

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

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

    private static void print(String temp) {
        temp = null;
    }
}

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

upvote
  flag
The static is throwing it off. public class Main { public static void main(String[] args) { Main m = new Main(); m.aaa(); } public void aaa() { String temp = "Vinay"; print(temp); System.err.println(temp); } private void print(String temp) { temp = null; } } the above code does not NPE. – Milhous
upvote
  flag
Didn't got what you are trying to say..? – Vinay Lodha
5 upvote
  flag
Doesn't answer the question. The OP is asking for an explanation, not just a proof. – EJP

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

2 upvote
  flag
I like this distinction in nomenclature. It's unfortunate that Java supports call by sharing for objects, but not call by value (as does C++). Java supports call by value only for primitive data types and not composite data types. – Derek Mahar
2 upvote
  flag
I really don't think we needed an extra term - it's simply pass-by-value for a specific type of value. Would adding "call by primitive" add any clarification? – Scott Stanchfield
7 upvote
  flag
upvote
  flag
So I can pass-by-reference by sharing some global context object, or even passing a context object that contains other references? I still pass-by-value, but at least I have access to references I can modify and make them point to something else. – YoYo

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

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

I hope this simple explanation helps.

2 upvote
  flag
'Pass by value' is a standard term in computer science and has been since the 1950s. No point in complaining about it now. – EJP

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

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

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

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

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

  1. A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).
  2. When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.
  3. So you're just passing 3bad086a that it's the value of the reference.
  4. You're passing the value of the reference and not the reference itself (and not the object).
  5. This value is actually COPIED and given to the method.

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

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

What happens?

  • The variable person is created in line #1 and it's null at the beginning.
  • A new Person Object is created in line #2, stored in memory, and the variable person is given the reference to the Person object. That is, its address. Let's say 3bad086a.
  • The variable person holding the address of the Object is passed to the function in line #3.
  • In line #4 you can listen to the sound of silence
  • Check the comment on line #5
  • A method local variable -anotherReferenceToTheSamePersonObject- is created and then comes the magic in line #6:
    • The variable/reference person is copied bit-by-bit and passed to anotherReferenceToTheSamePersonObject inside the function.
    • No new instances of Person are created.
    • Both "person" and "anotherReferenceToTheSamePersonObject" hold the same value of 3bad086a.
    • Don't try this but person==anotherReferenceToTheSamePersonObject would be true.
    • Both variables have IDENTICAL COPIES of the reference and they both refer to the same Person Object, the SAME Object on the Heap and NOT A COPY.

A picture is worth a thousand words:

Pass by Value

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

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

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

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

  • If it's a primitive data type these bits will contain the value of the primitive data type itself.
  • If it's an Object the bits will contain the value of the address that tells the JVM how to get to the Object.

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


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


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

3 upvote
  flag
Do you mean pointers?.. If I get it correctly, in public void foo(Car car){ ... }, car is local to foo and it contains the heap location of the Object? So if I change car's value by car = new Car(), it will point to different Object on the heap? and if I change car's property valu by car.Color = "Red", the Object in the heap pointed by car will be modified. Also, it is the same in C#? Please reply! Thanks! – dpp
7 upvote
  flag
@domanokz You're killing me, please don't say that word again! ;) Note that I could have answered this question without saying 'reference' as well. It's a terminology issue and 'p's make it worse. Me and Scot have different views on this unfortunately. I think you got how it works in Java, now you can call it pass by-value, by-object-sharing, by-copy-of-the-variable-value, or feel free to come up with something else! I don't really care as long as you got how it works and what's in a variable of type Object: just a PO Box address! ;) – Gevorg
upvote
  flag
Okay I get it, passed-by-value and the value shared when passed! >:D No more p's and r's in Java! My problem now is, how can I change the value of an external variable from a method? Thanks again. – dpp
upvote
  flag
when two objects refer to the same object, does that means it will occupy more memory in terms of an actual value? Or it will just occupy the memory for creating a pointer to the same place in memory? How does it work? – Ahmed
upvote
  flag
@BratRosm you used the "p" word. But I will answer your question anyway... When two variable refer to the same object the object itself is not added to the memory again, just a tiny amount for the variable. Gevorg's image shows it best if you think of the shapes as memory usage. The big rectangular shape is the actual object stored in the heap the little circles are multiple references to it, they are really just a matter bits. – Geronimo
upvote
  flag
one reason can be that java does not allow you to change that address so it gives you a copy of the reference(security) – curious
upvote
  flag
nice +1 for In line #4 you can listen to the sound of silence, I would have added, or go have a coffee, but admitedly are very quick coffee! For those who really want to change the value of a member of an object, you need to use setters and getters, called from your object. If you want a default value available that is the same in all objects that you creat of that object type, you need a static member. If that needs to be modified you will need a static method to do so. This is why those responses above that 'modify' the member of an object must use a static method inside of the main class. – DaveM
upvote
  flag
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
upvote
  flag
One more thing: the semantics in Java bear a similarity, in a way, to copy-on-write (COW) semantics, in that you're passing a copy of an address to a method. At the moment the method is called, the caller's variable and method-local variable point to the same object and are thus considered to be "sharing" the same pointer value. However, the moment you assign a different object to the local, passed-in variable, the variable's memory reference changes, but the caller variable's reference does NOT change. That's COW. – Aquarelle
4 upvote
  flag
Sounds like you just passed a reference? I'm going to championing the fact that Java is still a copied pass-by-reference language. The fact that it is a copied reference doesn't change the terminology. Both the REFERENCES still point to the same object. This is a purist's argument... – John Strickler
1 upvote
  flag
I guess Java designed with pointers in mind. Otherwise, why NullPointerException exists? Nevertheless, for this wonderful explanantion, getting pointers will just make it complicated – brain storm
2 upvote
  flag
So drop in on theoretical line #9 System.out.println(person.getName()); what will show up? "Tom" or "Jerry"? This is the last thing that will help me hurdle this confusion. – TheBrenny
upvote
  flag
I guess you've never heard of a NullPointerException. Java does indeed have pointers. But you probably won't take my word for it, so try this: "4.3.1 Objects An object is a class instance or an array. The reference values (often just references) are pointers to these objects, and a special null reference, which refers to no object." from the Java Language Spec 8, section 4.3.1. – Erick G. Hagstrom

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

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

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

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

void renameToJon(Person p) { 
    p = new Person("Jon"); // this will not work
}

jack = new Person("Jack");
renameToJon(jack);
sysout(jack); // jack is unchanged

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

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

To recap, everything is passed by value.

It's really quite, quite simple:

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

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

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


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

upvote
  flag
Also remembering that StringS are immutable in Java. – wulfgarpro
upvote
  flag
I find it helpful to think of class-type variables as holding "object IDs". Java's default string representation of objects works well with such a description. If one sets Foo to "Car #1234", and copies Foo to Bar, then both Foo and Bar will hold "Car #1234". Saying Foo.SetColor(Colors.Blue) will paint "Car #1234" blue. The other description I use for such storage locations is "promiscuous object references", since code which passes such a reference to an object has no way of controlling how the recipient might share it. – supercat
upvote
  flag
"promiscuous object references" is an exceptional term. – Aluan Haddad

Java always passes arguments by value NOT by reference.


Let me explain this through an example:

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

I will explain this in steps:

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

    Foo f = new Foo("f");
    

    enter image description here

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

    public static void changeReference(Foo a)
    

    enter image description here

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

    changeReference(f);
    

    enter image description here

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

    Foo b = new Foo("b");
    

    enter image description here

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

    enter image description here


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

    enter image description here

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

    enter image description here

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

41 upvote
  flag
+1 Nice stuff. good diagrams. I also found a nice succinct page here adp-gmbh.ch/php/pass_by_reference.html OK I admit it is written in PHP, but it is the priciple of understanding the difference that I think is important (and how to manipulate that difference to your needs). – DaveM
3 upvote
  flag
@Eng.Fouad It's a nice explanation but if a points to the same object as f (and never gets its own copy of the object f points to), any changes to the object made using a should modify f aswell (since they are both working with the same object), so at some point a must get its own copy of the object f points to. – Mr D
8 upvote
  flag
@MrD when 'a' points to the same object 'f' also points to, then any change made to that object via 'a' is also observable via 'f', BUT IT DID NOT CHANGE 'f'. 'f' still points to the same object. You can totally change the object, but you can never change what 'f' points to. This is the fundamental issue that for some reason some people just can't comprehend. – Mike Braun
upvote
  flag
@MikeBraun ...what? Now you've confused me :S. Isn't what you just wrote contrary to what 6. and 7. shows? – Evil Washing Machine
upvote
  flag
@EvilWashingMachine no, why? You never see modifyReference letting "f" point to a completely different instance, do you? There's only one object in 6 and 7. Locally new references to tgat object can be created ("c" in the example) and the content of that one object can be changed (as happens in 7), but nothing within the method has the power to re-assign "f" to a second object. – Mike Braun
upvote
  flag
@MikeBraun oh I see, I misunderstood when you said " BUT IT DID NOT CHANGE 'f'". I thought you also meant the object 'f' points to does not change. – Evil Washing Machine
upvote
  flag
If I say that object in Java is passed to a method by copy of the reference, that would probably solve the whole discussion. Nice diagrams above would fit-in and support that statement. – MaxZoom
upvote
  flag
The setAttribute method need to be accessed by Java reflection. tutorials.jenkov.com/java-reflection/… – herbertD
upvote
  flag
By this definition, all languages are pass by value and pass by reference does not exist. Pass by reference means you can edit the caller's instance of what you received. Whether this is done through a pointer or using C++'s convenient syntax is irrelevant. – Cdaragorn
3 upvote
  flag
This is the best explanation I've found. By the way, what about the basic situation? For example, the argument requires an int type, does it still pass the copy of an int variable to the argument? – allenwang
4 upvote
  flag
best explanation with diagrams, kudos! – Gurkha
1 upvote
  flag
Perfect. I found this answer more appealing than top two. – Arun
1 upvote
  flag
This is probably the best possible explanation. – Nikolay Frick
1 upvote
  flag
Kudos. Very very well written :-) – piechuckerr
1 upvote
  flag
Very nice explanation – afym
upvote
  flag
I am a little confused on line 5. I thought it goes from right to left; meaning object a is assigned object b and not the other way around. Or simply whatever the value of a is now whatever the value of b. Am I correct? – The_Martian

No, it's not pass by reference.

Java is pass by value according to the Java Language Specification:

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

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

1 upvote
  flag
There is no such thing as a 'constant referenece' in Java unless the programmer specifies 'finally'. – EJP
upvote
  flag
What I meant by constant reference is, there is no way to change the reference itself by saying new MyClass() in a function. If I put it correctly, there object references are passed by value which means a copy of the reference is passed so you can change the data where that reference refers to but you can not change it with new operator and allocate a new object. – fatma.ekici
upvote
  flag
So fix your answer. If it was a constant you couldn't reassign it inside the called method, and you can, unless you specify final. – EJP

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

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

class Example
{
    public static void test (Cat ref)
    {
        // 3 - <ref> is a copy of the reference <a>
        // both currently reference Grumpy
        System.out.println(ref.getName());

        // 4 - now <ref> references a new <Cat> object named "Nyan"
        ref = new Cat("Nyan");

        // 5 - this should print "Nyan"
        System.out.println( ref.getName() );
    }

    public static void main (String [] args)
    {
        // 1 - a is a <Cat> reference that references a Cat object in memory with name "Grumpy"
        Cat a = new Cat("Grumpy");

        // 2 - call to function test which takes a <Cat> reference
        test (a);

        // 6 - function call ends, and <ref> life-time ends
        // "Nyan" object has no references and the Garbage
        // Collector will remove it from memory when invoked

        // 7 - this should print "Grumpy"
        System.out.println(a.getName());
    }
}
upvote
  flag
'Pass its inner value' is meaningless. – EJP
upvote
  flag
@EJP thanks for the note, excuse my bad English from 2013, I've edited the whole thing, if you see a better wording, you may suggest or edit – Khaled.K
upvote
  flag
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 – Harish Amarnath

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

Passing Variables into Methods (Objective 7.3)

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

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

Passing Object Reference Variables

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

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

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

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

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

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

Does Java Use Pass-By-Value Semantics?

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

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

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

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

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

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

Passing Primitive Variables

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

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

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

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

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

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

public void test() {
    MyClass obj = null;
    init(obj);
    //After calling init method, obj still points to null
    //this is because obj is passed as value and not as reference.
}
private void init(MyClass objVar) {
    objVar = new MyClass();
}
2 upvote
  flag
This is the clearest, simplest way to see that Java passes by value. The value of obj (null) was passed to init, not a reference to obj. – David Schwartz

Shortest answer :)

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

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

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

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

class Example
{
    static void InitArray(out int[] arr)
    {
        arr = new int[5] { 1, 2, 3, 4, 5 };
    }

    static void Main()
    {
        int[] someArray;
        InitArray(out someArray);

        // This is true !
        boolean isTrue = (someArray[0] == 1);
    }
}

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

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

upvote
  flag
in java we can do: someArray = InitArray(someArray) assuming we have this: static int [] InitArray( int[] arr){ ... return ...} – Kachna
upvote
  flag
You are correct. That's a possible alternative for a simple pass-by-reference. But pass-by-reference can do more powerful things. e.g. it could assign multiple values: e.g. int[] array1; int[] array2; InnitArrays(out array1, out array2); assuming that you create a method static void InitArray(out int[] a1, out int[] a2){...} – bvdb

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

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

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

package test.abc;

public class TestObject {

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

    static void bar() {
        Foo f = new Foo();
        System.out.println("Object reference for f: " + f);
        f.setName("James");
        doStuff(f);
        System.out.println(f.getName());
        //Can change the state of an object variable in f, but can't change the object reference for f.
        //You still have 2 foo objects.
        System.out.println("Object reference for f: " + f);
        }

    static void doStuff(Foo g) {
            g.setName("Boo");
            g = new Foo();
            System.out.println("Object reference for g: " + g);
        }
}


package test.abc;

public class Foo {
    public String name = "";

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

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

Console output:

Object reference for f: test.abc.Foo@62f72617

Object reference for g: test.abc.Foo@4fe5e2c3

Boo Object reference for f: test.abc.Foo@62f72617

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

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

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

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

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

results in this:

primitives on the stack

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

Like so:

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

a b*7ch aint one!

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

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

marx brothers

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

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

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

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

la da di da da da da

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

4 upvote
  flag
However, you should have followed up with a more complex example where a function appears to alter a variable to whose address it has a reference. – Brian Peterson
23 upvote
  flag
People are not "dancing around the real issue" of stack vs heap, because that's not the real issue. It's an implementation detail at best, and downright wrong at worst. (It's quite possible for objects to live on the stack; google "escape analysis". And a huge number of objects contain primitives that probably don't live on the stack.) The real issue is exactly the difference between reference types and value types -- in particular, that the value of a reference-type variable is a reference, not the object it refers to. – cHao
2 upvote
  flag
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
2 upvote
  flag
Actually, I lied: it is in the spec. The stack is for locals and partial results link, and the heap is for objects link – cutmancometh
6 upvote
  flag
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
7 upvote
  flag
And either way, "primitives go on the stack" is incorrect. Primitive local variables go on the stack. (If they haven't been optimized away, of course.) But then, so do local reference variables. And primitive members defined within an object live wherever the object lives. – cHao
7 upvote
  flag
Agree with the comments here. Stack/heap is a side issue, and not relevant. Some variables may be on the stack, some are in static memory (static variables), and plenty live on the heap (all object member variables). NONE of these variables can be passed by reference: from a called method it is NEVER possible to change the value of a variable that is passed as an argument. Therefore, there is no pass-by-reference in Java. – fishinear
2 upvote
  flag
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. – Aluan Haddad
1 upvote
  flag
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. – Dawood ibn Kareem
upvote
  flag
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
upvote
  flag
Also, I'm not saying Java is pass-by-reference. I've been saying from the beginning that "pass-by-reference vs. pass-by-value" is a stupid argument because it doesn't yield any useful understanding, so here's a model of what's happening intended to help you understand why local primitives behave one way and objects behave another way, when passed into a method. Simply saying "Java is pass by reference" is incomplete because it often requires additional explanation. I was attempting to provide some additional information, rather than just a short sound-byte. – cutmancometh
upvote
  flag
@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
upvote
  flag
if not in this answer then somewhere. Please explain to me why swap method fails! – Faraz Durrani
upvote
  flag
Sure, can you be more specific? Could post post the code you're referring to in ideone.com, or even just pastebin.com? There's plenty of room for abiguity in the term "swap method", and I'd hate to give you incomplete information. – cutmancometh
upvote
  flag
@cutmancometh if it is a stupid argument, how can we describe the distinction? It exists in other languages. It is significant to Java in that other languages share a largely common call syntax. Consider C#'s ref. – Aluan Haddad

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

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

main()
  arr +---+       +---+---+---+
      | # | ----> | 3 | 4 | 5 |
      +---+       +---+---+---+
  b   +---+             ^
      | 1 |             | 
      +---+             |
                        |
dummyIncrease()         |
  x   +---+             |
      | # | ------------+
      +---+      
  y   +---+ 
      | 1 | 
      +---+ 

Java is always pass by values NOT pass by reference

first of we understand what is pass by value and pass by reference

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

pass by reference (also called pass by address), a copy of the address of the actual parameter is stored

Some time it gives illusion pass by reference.lets see how it works by example

public class Passbyvalue {
    public static void main(String[] args) {
        test t=new test();
        t.name="initialvalue";
        new Passbyvalue().changeValue(t);
        System.out.println(t.name);
    }

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

class test{
    String name;
}

Output of this program is

changevalue

lets understand step by step

test t=new test();

as we all know it will create object in heap and return return reference value back to t. suppose for example value of t is 0x100234(its JVM internal value as we don't about it i have just consider it for example)

enter image description here

new Passbyvalue().changeValue(t);

when passing reference t to function it will not directly pass actual reference value of object test but it will create copy of t and then it pass to function ( as it pass by value it passes copy of variable not actual reference of it) . As we consider value of t will be0x100234 . so in this way both t and f will have same value and hence they will point to same object

enter image description here

so if you change any thing in function using reference f it will modify existing contain of object that why we were getting output "changevalue" which is updated in function

to understand this more clearly consider following example

public class Passbyvalue {
    public static void main(String[] args) {
        test t=new test();
        t.name="initialvalue";
        new Passbyvalue().changerefence(t);
        System.out.println(t.name);
    }

    public void changerefence(test f){
        f=null;
    }
}

class test{
    String name;
}

will it give null pointer no because it passes only copy of reference .In case of by reference it could have given nullpointer exception

enter image description here

Hopefully this will help

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


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


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

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

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


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

This code outputs the following:
java PassTest
Int value is: 11
MyDate: 22-7-1964
MyDate: 4-7-1964
The MyDate object is not changed by the changeObjectRef method;
however, the changeObjectAttr method changes the day attribute of the
MyDate object.
upvote
  flag
This is very misleading. You certainly can change the value of an argument from within a method. – Gray

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

  1. Creates new Point object
  2. Creates new Point reference and initialize that reference to point (refer to) on previously created Point object.
  3. From here, through Point object life, you will access to that object through pnt1 reference. So we can say that in Java you manipulate object through its reference.

enter image description here

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

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

Flow of the program:

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

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

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

As expected output will be:

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

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

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

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

In the tricky method:

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

enter image description here

Next in the tricky method

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

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

enter image description here

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

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

So now, completely execution of program will be:

X1: 0         Y1: 0
X2: 0         Y2: 0
X1: 100       Y1: 100
X2: 0         Y2: 0
6 upvote
  flag
In java when you say "In java everything is reference" you mean all objects are passed by reference. Primitive data types are not passed by reference. – Eric
upvote
  flag
I am able to print swapped value in main method. in trickey method , add the following statement arg1.x = 1; arg1.y = 1; arg2.x = 2; arg2.y = 2; so, as arg1 now holding of pnt2 refrence and arg2 holding now pnt1 reference, so, its printing X1: 2 Y1: 2 X2: 1 Y2: 1 – Shahid Ghafoor

Java passes references to objects by value.

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

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

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

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

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

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

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

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

This is how jump-tables work.

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

  1. 5 gets copied to one of the CPU registers (ie. EAX).
  2. 5 gets PUSHd to the stack.
  3. 47 gets copied to one of the CPU registers
  4. 47 PUSHd to the stack.
  5. 223 gets copied to one of the CPU registers.
  6. 223 gets PUSHd to the stack.

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

Now we have passed Foo to the method:

  • in case 1. and 2. if you change Foo (Foo = 9) it only affects local scope as you have a copy of the Value. From inside the method we cannot even determine where in memory the original Foo was located.
  • in case 3. and 4. if you use default language constructs and change Foo (Foo = 11), it could change Foo globally (depends on the language, ie. Java or like Pascal's procedure findMin(x, y, z: integer;var m: integer);). However if the language allows you to circumvent the dereference process, you can change 47, say to 49. At that point Foo seems to have been changed if you read it, because you have changed the local pointer to it. And if you were to modify this Foo inside the method (Foo = 12) you will probably FUBAR the execution of the program (aka. segfault) because you will write to a different memory than expected, you can even modify an area that is destined to hold executable program and writing to it will modify running code (Foo is now not at 47). BUT Foo's value of 47 did not change globally, only the one inside the method, because 47 was also a copy to the method.
  • in case 5. and 6. if you modify 223 inside the method it creates the same mayhem as in 3. or 4. (a pointer, pointing to a now bad value, that is again used as a pointer) but this is still a local problem, as 223 was copied. However if you are able to dereference Ref2Foo (that is 223), reach to and modify the pointed value 47, say, to 49, it will affect Foo globally, because in this case the methods got a copy of 223 but the referenced 47 exists only once, and changing that to 49 will lead every Ref2Foo double-dereferencing to a wrong value.

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

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

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

upvote
  flag
In a language with pass-by-reference, the thing which is passed (the reference) is ephemeral; the recipient is not "supposed" to copy it. In Java, passing an array is passed is an "object identifier"--equivalent to a slip of paper which says "Object #24601", when the 24601st object constructed was an array. The recipient can copy "Object #24601" anywhere it wants, and anyone with a slip of paper saying "Object #24601" can do anything it wants with any of the array elements. The pattern of bits that is passed wouldn't actually say "Object #24601", of course, but... – supercat
upvote
  flag
...the key point is that the recipient of the object-id that identifies the array can store that object-id wherever it wants and give it to whomever it wants, and any recipient would be able to access or modify the array whenever it wants. By contrast, if an array were passed by reference in a language like Pascal which supports such things, the called method could do whatever it wanted with the array, but could not store the reference in such a way as to allow code to modify the array after it returned. – supercat
upvote
  flag
Indeed, in Pascal you can get the address of every variable, be it passed-by-reference or locally copied, addr does it untyped,@ does it with type, and you can modify the referenced variable later (except locally copied ones). But I don't see the point why you would do that. That slip of paper in your example (Object #24601) is a reference,its purpose is to help find the array in memory, it does not contain any array data in itself. If you restart your program, the same array might get a different object-id even if its content will be the same as it has been in the previous run. – karatedog
upvote
  flag
I'd thought the "@" operator was not part of standard Pascal, but was implemented as a common extension. Is it part of the standard? My point was that in a language with true pass-by-ref, and no ability to construct a non-ephemeral pointer to an ephemeral object, code which holds the only reference to an array, anywhere in the universe, before passing the array by reference can know that unless the recipient "cheats" it will still hold the only reference afterward. The only safe way to accomplish that in Java would be to construct a temporary object... – supercat
upvote
  flag
...which encapsulates an AtomicReference and neither exposes the reference nor its target, but instead includes methods to do things to the target; once the code to which the object was passed returns, the AtomicReference [to which its creator kept a direct reference] should be invalidated and abandoned. That would provide the proper semantics, but it would be slow and icky. – supercat

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

public class Dog {

    String dog ;
    static int x_static;
    int y_not_static;

    public String getName()
    {
        return this.dog;
    }

    public Dog(String dog)
    {
        this.dog = dog;
    }

    public void setName(String name)
    {
        this.dog = name;
    }

    public static void foo(Dog someDog)
    {
        x_static = 1;
        // y_not_static = 2;  // not possible !!
        someDog.setName("Max");     // AAA
        someDog = new Dog("Fifi");  // BBB
        someDog.setName("Rowlf");   // CCC
    }

    public static void main(String args[])
    {
        Dog myDog = new Dog("Rover");
        foo(myDog);
        System.out.println(myDog.getName());
    }
}

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

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

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

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

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

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

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

And on the subject of pass-by-value

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

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

When the method or constructor is invoked (§15.12), the values of the actual argument expressions initialize newly created parameter variables, each of the declared type, before execution of the body of the method or constructor.

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

What is the value of the argument?

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

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

The Java Language Specification also states

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

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

So

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

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

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

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

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


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

upvote
  flag
Thank you for beginning with a discussion of the definitions of the terms. That sets your answer apart from the crowd and is necessary for a proper understanding. – Aaron

Understand it in 2 Steps:

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

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

public static void foo(Dog d) {
  d.Name = "belly";
  System.out.println(d); //Reference: Dog@1540e19d

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

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

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

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

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

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

Examples of Passing by copy/ by value

Example from [ref 1]

void incrementValue(int inFunction){
  inFunction ++;
  System.out.println("In function: " + inFunction);
}

int original = 10;
System.out.print("Original before: " + original);
incrementValue(original);
System.out.println("Original after: " + original);

We see in the console:
 > Original before: 10
 > In Function: 11
 > Original after: 10 (NO CHANGE)

Example from [ref 2]

shows nicely the mechanism watch max 5 min

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

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

void incrementValu(int[] inFuncion){
  inFunction[0]++;
  System.out.println("In Function: " + inFunction[0]);
}

int[] arOriginal = {10, 20, 30};
System.out.println("Original before: " + arOriginal[0]);
incrementValue(arOriginal[]);
System.out.println("Original before: " + arOriginal[0]);

We see in the console:
  >Original before: 10
  >In Function: 11
  >Original before: 11 (CHANGE)

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

Example from[ref 3]

package com.pritesh.programs;

class Rectangle {
  int length;
  int width;

  Rectangle(int l, int b) {
    length = l;
    width = b;
  }

  void area(Rectangle r1) {
    int areaOfRectangle = r1.length * r1.width;
    System.out.println("Area of Rectangle : " 
                            + areaOfRectangle);
  }
}

class RectangleDemo {
  public static void main(String args[]) {
    Rectangle r1 = new Rectangle(10, 20);
    r1.area(r1);
  }
}

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

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

  1. REF 1 Lynda.com
  2. REF 2 Professor Mehran Sahami
  3. REF 3 c4learn
upvote
  flag
Java by default is said to be pass by reference. usually when a mutable object is passed to some methods then any changes done with that object reference will be reflected to the other parts too using same object reference. But in case of immutable object, if reference is reassigned to some other objects, then it will not be reflected to the other parts, entirely new objects will be created. – Shailendra Singh
1 upvote
  flag
@ShailendraSingh Java never passes by reference, period. See Gaurav's answer for a clear proof of this. – David Schwartz
upvote
  flag
"pass-by-copy-of-the-variable-value" is slightly misleading. An actual argument is a value, which is the result of evaluating an expression. There need be no variable in the expression. – Tom Blodget

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

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

    int[] tab = new int[]{1};
    foo(tab);
    System.out.println(tab[0]); // out 3 (tab[0] did change in foo)
}}

I hope this helps!

Simple program

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

        //test passing an integer
        int i=0;
        foo_int(i);
        System.out.println(i);//prints 0
    }
}

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

1 upvote
  flag
You can only define one class per file. This is not including nested and inner classes. Considering this will be something a new programmer will be reading, you should explain this to the user; allowing them to duplicate the code on their machine. – mrres1
2 upvote
  flag
@mrres1 Not entirely correct. You can define only one public top-level class/interface per file. Supporting several classes per file is a remnant from the first Java version, which didn't have nested classes, but it is still supported, though often frowned upon. – MrBackend

Java passes everything by value!!

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

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

PersonClass variable2;

//Both variable2 and variable1 now reference the same object

variable2 = variable1; 


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

// variable1 now points to variable3

variable1 = variable3;

//WHAT IS OUTPUT BY THIS?

System.out.println(variable2);
System.out.println(variable1);

Mary 32
Andre 45

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

webPage

upvote
  flag
This actually doesn't explain anything in regards to potential by ref/by val property of Java. – Mox

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!

upvote
  flag
I think you nailed it by saying you can't change the reference from the object itself – sakhunzai
upvote
  flag
So an object can be changed by using its public interfaces but could not be replace with sth else i.e deference and by this java achieves best of both worlds – sakhunzai

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

/**

Pass By Value

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

*/

Example 1:

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

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

    }

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

Result

output : output
value : Nikhil
valueflag : false

Example 2:

/** * * Pass By Value * */

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

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

    }

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

Result

output : output
value : Nikhil
valueflag : false

Example 3:

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

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

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

*/

public class PassByValueObjectCase1 {

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

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

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

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

Result

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

Example 4:

/**

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

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

*/

public class PassByValueObjectCase2 {

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

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

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

}

Result

output : output
student : Student [id=10, name=Nikhil]
2 upvote
  flag
This should be a correct answer, examples 3 and 4 completely eliminated any further argument on the topic. – norbertas.gaulia

ACCORDING TO C++ TERMINOLOGY :

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

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

3 upvote
  flag
Please provide a definitive reference for this; i.e. a specific reference to a specific section of an official C++ specification. (I suspect that this is how you would describe the >>representations<< in C++ if you were simulating the behavior of Java parameter using C++ features. But that is missing the point. What we are talking about here is language models, and it is well know that Java and C++'s respective language models are (very) different.) – Stephen C

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

Consider next 3 situations:

1) Trying to change primitive variable

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

int a = 3;
increment(a);

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

2) Trying to change primitive field of an object

public static void increment(Person p) { p.age++; }

Person pers = new Person(20); // age = 20
increment(pers);

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

3) Trying to change reference value of reference variables

public static void swap(Person p1, Person p2) {
    Person temp = p1;
    p1 = p2;
    p2 = temp;
}

Person pers1 = new Person(10);
Person pers2 = new Person(20);
swap(pers1, pers2);

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

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

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

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

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

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

Diagram of how data is created and passed

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

That means:

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

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

A good description of both can be found here.

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

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

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

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

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

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

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

1 upvote
  flag
Java has not redefined those terms. Nobody has. It has merely avoided the C term 'pointer'. – EJP
4 upvote
  flag
Those terms existed long before Java or C. Pointer was only ever a method for implementing one of them. If you accept Java's definition for them, then they become meaningless because by that definition, every language ever created is only Pass by Value. – Cdaragorn

Thinking that way is just making things sound more and more complicated. Just simply thinks that the new keyword creates a whole new object thus, when you pass an object from a variable to another variable without the keyword new, you pass the same object.

Assume the operator = means the word "is" in English :

Pokemon a = new Pokemon(); // Pokemon a is a new Pokemon
Pokemon b = a; //Pokemon b is pokemon a

So, if you made any changes towards b, affects a, since b is a or you can think b as an alias for a.

Let's see what happen when we change the operands into primitive variables like int, float, etc. :

int x = 1; // x is 1
int y = x; // y is 1
y = 5 // y is 5

x is an alias for 1, whenever I say "x", it means 1. So, changes towards y will not affect x...

Another analogy :

Suppose that Tommy Spade, Dennis Heart and Jackie Diamond are friends. Tommy calls Jackie "Jack" and Dennis call Jackie "Dia". Let's think Jack and Dia are variables. No matter what, Jackie and Dia is the same entity (object). When Tommy hit Jack's face, Dennis can see the bruise in Dia's face too of course, since Jack and Dia is the same [person].

Primitive values are just primitive. It has no component, just a value, so the above analogy doesn't work on this type of data.

One of the main concept of OOP is abstraction. You don't need to know the details of how a device work to use it, you only need to know how to use it, not how it works. Unless you want to be a researcher, it is fine. Hope my answer helps.

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

#include <iostream>
using namespace std;

class Foo {
    private:
        int x;
    public:
        Foo(int val) {x = val;}
        void foo()
        {
            cout<<x<<endl;
        }
};

void bar(Foo& ref)
{
    ref.foo();
    ref = *(new Foo(99));
    ref.foo();
}

int main()
{
   Foo f = Foo(1);
   f.foo();
   bar(f);
   f.foo();

   return 0;
}

What is the outcome?

1
1
99
99

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

Now, lets see what java says.

public class Ref {

    private static class Foo {
        private int x;

        private Foo(int x) {
            this.x = x;
        }

        private void foo() {
            System.out.println(x);
        }
    }

    private static void bar(Foo f) {
        f.foo();
        f = new Foo(99);
        f.foo();
    }

    public static void main(String[] args) {
        Foo f = new Foo(1);
        System.out.println(f.x);
        bar(f);
        System.out.println(f.x);
    }

}

It says:

1
1
99
1

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

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

upvote
  flag
Is there an issue in your c++ version where your risking a segfault when Foo(99) goes out of scope but you reference it in your main method? – matt
upvote
  flag
Indeed. Ah comes from using java for 10 years. But the idea still holds. And I fixed it now. – Ravi Sanwal
upvote
  flag
I think the previous was better because it would compile. I was just curious about the behavior, sorry about that. – matt
upvote
  flag
This answer only helps for those coming from C++ background who are willing to define "reference" the way you have, according to C++'s definition. That is not always the case. – Aaron

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.

upvote
  flag
So it's byRef in regards to objects and byVal in regards to primitives? – Mox
upvote
  flag
@mox please read: Objects are not passed by reference, this is a ledgend: String a=new String("unchanged"); – user1767316
upvote
  flag
public void changeit(String changeit){changit = "changed";} changeIt(a); assert(a.equals("unchanged")); – user1767316
upvote
  flag
This is yet another great example of the fallacy of the "it is not pass by reference" semantics argument. This answer says right in the bold, first sentence: "only references are passed." Either a reference is passed, or a reference is not passed. You just said yourself that a reference is passed. By saying "it is not passed by reference since a reference is passed but..." you are trying to make a point by mangling English. – Aaron
upvote
  flag
@Aaron "Pass by reference" does not mean "pass a value that is a member of a type that is called a 'reference' in Java". The two uses of "reference" mean different things. – philipxy
upvote
  flag
@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. – Aaron
upvote
  flag
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
upvote
  flag
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. – zakmck
public static void main(String args[]) {

    Point p1 = new Point(1, 1); //This is pointing to a location in memory let's say that the reference is x1=5
    Point p2 = new Point(2, 2); //This is pointing to a location in memory let's say that the reference is x2=6

    // Next we need to pass something to the function, what is it and how we pass it? 
    // There are two references x1,x2 are going to be passed by value
    // Meaning that if x1=5, x2=6 as we mentioned, we are passing 5,6. We are not passing x1,x2
    // That's a big difference. If we are passing x1 and x2, we can change values there inside the trickMe method.
    // but we are passing only two numbers which are 5 and 6.
    trickMe(p1, p2);

    System.out.println(p1); // outputs java.awt.Point[x=1,y=1]
    System.out.println(p2); // outputs java.awt.Point[x=2,y=2]
}

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

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

Take the badSwap() method for example:

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

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

public void tricky(Point arg1, Point   arg2)
{ arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; }
public static void main(String [] args) { 

 Point pnt1 = new Point(0,0); Point pnt2
 = new Point(0,0); System.out.println("X:
 " + pnt1.x + " Y: " +pnt1.y);

     System.out.println("X: " + pnt2.x + " Y:
 " +pnt2.y); System.out.println(" ");

     tricky(pnt1,pnt2);
 System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);

     System.out.println("X: " + pnt2.x + " Y: " +pnt2.y); }

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

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

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

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

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

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

(Non-Java) Basic swap function structure

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

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

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

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

upvote
  flag
Good answer. Beautifully explained. – Ankur Mahajan
upvote
  flag
You might want to clarify your last sentence. My first reaction to "passing the values only and not pointers..." is that your Java implementation probably does exactly that, passes a pointer. The fact that you cannot dereference that pointer seems irrelevant. – Aaron
public class Main {

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Murat");
        System.out.println(person);
        passby(person);
        System.out.println(person);

    }

    public static void passby(Person a){
        //a= new Person(); //if you open this line you will see that reference value change so main reference not change
        a.setName("Kemal");
        System.out.println(a);
    }

    private static class Person {
        String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return getName();
        }
    }
}
upvote
  flag
You need to add sample output in order for this to be helpful. I get what you're trying to show, but someone who has the question would not. – Carlos Bribiescas
class Codechef
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        Person p = new Person();
        p.age = 30;
        System.out.println(p.age); //30
        ss(p); //40
        System.out.println(p.age); //40
        yy(p); //20
        System.out.println(p.age); //40
    }
    static void  ss(Person p) {
// Change the value in object then it gets retained.
        p.age = 40;
        System.out.println(p.age);
    }

    static void  yy(Person p) {
// Change the object itself it don't retain. So its pass by value
        p = new Person();
        p.age = 20;
        System.out.println(p.age);
    }
}


class Person {
    int age = 10;   
}

O/p

30 40 40 20 40

So its always the pass by value but if the object instance variables are changed they get retained. If the Object itself is changed then java creates a new object so its not retained.

The major cornerstone knowledge must be the quoted one,

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

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

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

Class-S

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

Class-Sample

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

Output

alam

alam

taleev

alam

taleev

harry

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

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

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

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

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

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

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

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

The output is:

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

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

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

@Test
public void sampleTest2(){
    Person person = new Person(24, "John");
    System.out.println(person);
    alterPerson(person);
    System.out.println(person);
}

/**
 * @param person
 */
private void alterPerson(Person person) {
    person.setAge(45);
    Person altered = person;
    altered.setName("Tom");
}

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

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

    public int getAge() {
        return age;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

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

}

In this case, the output is:

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

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

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

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

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

public class Doggie {

    public static void main(String...args) {
        System.out.println("At the owner's home:");
        Dog d = new Dog(12);
        d.wag();
        goodVet(d);
        System.out.println("With the owner again:)");
        d.wag();
        badVet(d);
        System.out.println("With the owner again(:");
        d.wag();
    }

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

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

class Dog {

    int tailLength;

    public Dog(int originalLength) {
        this.tailLength = originalLength;
    }

    public void cutTail (int newLength) {
        this.tailLength = newLength;
    }

    public void wag()  {
        System.out.println("Wagging my " +tailLength +" inch tail");
    }
}

Output:
At the owner's home:
Wagging my 12 inch tail
At the good vet:
Wagging my 12 inch tail
Wagging my 6 inch tail
With the owner again:)
Wagging my 12 inch tail
At the bad vet:
Wagging my 12 inch tail
Wagging my 2 inch tail
With the owner again(:
Wagging my 2 inch tail

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

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

Java is pass by value.

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

class Test    {

public static void main (String[] args) throws java.lang.Exception
{
    // Primitive type
    System.out.println("Primitve:");
    int a = 5;
    primitiveFunc(a);
    System.out.println("Three: " + a);    //5

    //Object
    System.out.println("Object:");
    DummyObject dummyObject = new DummyObject();
    System.out.println("One: " + dummyObject.getObj());    //555
    objectFunc(dummyObject);
    System.out.println("Four: " + dummyObject.getObj());    //666 (555 if line in method uncommented.)

}

private static void primitiveFunc(int b)    {
    System.out.println("One: " + b);    //5
    b = 10;
    System.out.println("Two:" + b);    //10
}

private static void objectFunc(DummyObject b)   {
    System.out.println("Two: " + b.getObj());    //555
    //b = new DummyObject();
    b.setObj(666);
    System.out.println("Three:" + b.getObj());    //666
}

}

class DummyObject   {
    private int obj = 555;
    public int getObj() { return obj; }
    public void setObj(int num) { obj = num; }
}

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

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

upvote
  flag
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 – Flyout

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

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

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

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

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

public class Balloon {

    private String color;

    public Balloon(){}

    public Balloon(String c){
        this.color=c;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }
}

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

public class Test {

    public static void main(String[] args) {

        Balloon red = new Balloon("Red"); //memory reference 50
        Balloon blue = new Balloon("Blue"); //memory reference 100

        swap(red, blue);
        System.out.println("red color="+red.getColor());
        System.out.println("blue color="+blue.getColor());

        foo(blue);
        System.out.println("blue color="+blue.getColor());

    }

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

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

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

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

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

Let’s analyze the program execution step by step.

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

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

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

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

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

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

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

Now let’s analyze foo() method execution.

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

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

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

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

In java, arguments are always passed by value regardless of the original variable type. Each time a method is invoked, the following happens:

  • A copy for each argument is created in the stack memory and the copy version is passed to the method.
  • If the original variable type is primitive, then simply, a copy of the variable is created inside the stack memory and then passed to the method.
  • If the original type is not primitive, then a new reference is created inside the stack memory which points to the actual object data and the new reference is then passed to the method, (at this stage, 2 references are pointing to the same object data).

Inside the method, you can modify the data of the referenced object but you can't modify the reference itself.

This tutorial explains well why java is always pass by value.

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

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.

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

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

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

Example using primitive data type:

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


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

    }
}

Example using object:

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

    }


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

Not the answer you're looking for? Browse other questions tagged or ask your own question.