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?
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
So if you have
Naturally, passing by value a reference to an object looks very much like (and is indistinguishable in practice from) passing an object by reference.
Java passes references by value.
So you can't change the reference that gets passed in.
Basically, reassigning Object parameters doesn't affect the argument, e.g.,
will print out
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:
In this example
In the above example,
To make a long story short, Java objects have some very peculiar properties.
In general, Java has primitive types (
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.
Take this to C++, and we have references. References are basically (in this context) syntactic sugar that hide the pointer part of the equation:
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.
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):
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.
output of java PassByCopy:
Primitive wrapper classes and Strings are immutable so any example using those types will not work the same as other types/objects.
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:
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
is not a Dog; it's actually a pointer to a Dog.
What that means, is when you have
you're essentially passing the address of the created
(I say essentially because Java pointers aren't direct addresses, but it's easiest to think of them that way)
if the Method were defined as
let's look at what's happening.
Now let's think about what happens outside the method:
There's the key.
Keeping in mind that
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
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.
In C++: Note: Bad code - memory leaks! But it demonstrates the point.
Java only has the two types of passing: by value for built-in types, and by value of the pointer for object types.
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.
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++:
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:
As was explained in previous answers, in Java you're passing a pointer to the array as a value into
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:
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:
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:
However you could make a wrapper for String like this which would make it able to use it with Strings:
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.
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?
Java copies the reference by value. So if you change it to something else (e.g, using
Have a look at this code. This code will not throw
If Java is pass by reference then it should have thrown
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".
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.
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.
Now think of what an Object's reference/variable does/is:
In the following (please don't try to compile/execute this...):
A picture is worth a thousand words:
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!
Of course you can cut it short and just say that Java is pass-by-value!
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.
The reference of the object itself, is passed by value: you can reassign the parameter, but the change is not reflected back:
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.
For a variable of reference type (eg.
Either way, you're always passing stuff by value.
Compare this to say C++ where you can have a method to take an
Java always passes arguments by value NOT by reference.
Let me explain this through an example:
I will explain this in steps:
I hope you understand now how passing objects as arguments works in Java :)
No, it's not pass by reference.
Java is pass by value according to the Java Language Specification:
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.
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 ..
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.
C:\Java Projects\Reference>java ReferenceTest Before modify() d.height = 10 dim = 11 After modify() d.height = 11
Java has only pass by value. A very simple example to validate this.
Shortest answer :)
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.
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.
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!
Note that the object reference has not changed in the console output below:
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:
results in this:
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.
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.
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.
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
So, value, reference? You say "potato".
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.
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
Output of this program is
lets understand step by step
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)
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
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
will it give null pointer no because it passes only copy of reference .In case of by reference it could have given nullpointer exception
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.
In java everything is reference, so when you have something like:
Java doesn't pass method arguments by reference; it passes them by value. I will use example from this site:
Flow of the program:
Creating two different Point object with two different reference associated.
As expected output will be:
On this line 'pass-by-value' goes into the play...
Next in the
Here, you first create new
From here scope of
So after executing method
So now, completely execution of program will be:
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
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:
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:
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.
Mr @Scott Stanchfield wrote an excellent answer. Here is the class that would you to verify exactly what he meant:
So, we pass from main() a dog called
I thought I'd contribute this answer to add more details from the Specifications.
Or from wikipedia, on the subject of pass-by-reference
Second, we need to know what Java uses in its method invocations. The Java Language Specification states
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
The Java Language Specification also states
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 (
all bind the value of a reference to a
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
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).
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
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  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.
Examples of Passing by copy/ by value
Example from [ref 1]
Example from [ref 2]
(Passing by reference) pass-by-copy-of-the-variable-value
Example from [ref 1] (remember that an array is an object)
The complex objects themselves are being copied, but the internal references are being retained.
Example from[ref 3]
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.
There is a workaround in Java for the reference. Let me explain by this example:
I hope this helps!
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.
Java passes everything by value!!
//create an object by passing in a name and age:
//Both variable2 and variable1 now reference the same object
// variable1 now points to variable3
//WHAT IS OUTPUT BY THIS?
if you could understand this example we r done. otherwise, please visit this webPage for detailed explanation:
Java passes parameters by VALUE, and by value ONLY.
To cut long story short:
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
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.
/** * * Pass By Value * */
/** 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.
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
ACCORDING TO C++ TERMINOLOGY :
(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)
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
x will copy value of a and will increment x, a remains the same
2) Trying to change primitive field of an object
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
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:
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
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.
Thinking that way is just making things sound more and more complicated. Just simply thinks that the
Assume the operator = means the word "is" in English :
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. :
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.
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.
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.
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.
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:
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:
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
If you can write such a method/function in your language such that calling
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.
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,
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
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:
The output is:
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:
In this case, the output is:
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.
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
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.
Java is a call by value.
How it works.
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:
If the line
Illustrations in one of the answers in this thread (//allinonescript.com/a/12429953/4233180) can help gain a deeper understanding.
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.
And we have a simple program with a generic method to swap two objects, the class looks like below.
When we execute the above program, we get following output.
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.
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.
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.
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:
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:
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
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.
Example using primitive data type:
Example using object: