By user4315


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

I always thought Java was pass-by-reference.

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

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

What is the explanation?

30 comments

@Sanjeev 2019-01-25 21:37:30

There are already great answers that cover this. I wanted to make a small contribution by sharing a very simple example (which will compile) contrasting the behaviors between Pass-by-reference in c++ and Pass-by-value in Java.

A few points:

  1. The term "reference" is a overloaded with two separate meanings. In Java it simply means a pointer, but in the context of "Pass-by-reference" it means a handle to the original variable which was passed in.
  2. Java is Pass-by-value, but allows us to emulate pass be reference by passing a Java reference (i.e. a pointer) by value. Meaning it passes a copy of the Java reference. EDIT: since someone made a comment about this, let me explain. Before C, several (but not all) earlier languages like FORTRAN and COBOL supported PBR, but C did not. In order to change the values of variables inside functions, C programmers emulated PBR by passing pointers to variables into functions. Languages inspired by C, such as Java, borrowed this idea and continue to emulate PBR as C did.
  3. C++ allows Pass-by-reference by declaring a reference parameter using the "&" character (which happens to be the same character used to indicate "the address of a variable" in both C and C++). For example, if we pass in a pointer by reference, the parameter and the argument are not just pointing to the same object. Rather, they are the same variable. If one gets set to a different address or to null, so does the other.
  4. In the C++ example below I'm passing a pointer to a null terminated string by reference. And in the Java example below I'm passing a Java reference to a String (again, the same as a pointer to a String) by value. Notice the output in the comments.

C++ pass by reference example:

using namespace std;
#include <iostream>

void change (char *&str){   // the '&' makes this a reference parameter
    str = NULL;
}

int main()
{
    char *str = "not Null";
    change(str);
    cout<<"str is " << str;      // ==>str is <null>
}

Java pass "a Java reference" by value example

public class ValueDemo{

    public void change (String str){
        str = null;
    }

     public static void main(String []args){
        ValueDemo vd = new ValueDemo();
        String str = "not null";
        vd.change(str);
        System.out.println("str is " + str);    // ==> str is not null!!
                                                // Note that if "str" was
                                                // passed-by-reference, it
                                                // WOULD BE NULL after the
                                                // call to change().
     }
}

EDIT

Several people have written comments which seem to indicate that either they are not looking at my examples or they don't get the c++ example. Not sure where the disconnect is, but guessing the c++ example is not clear. I'm posting the same example in pascal because I think pass-by-reference looks cleaner in pascal, but I could be wrong. I might just be confusing people more; I hope not.

In pascal, parameters passed-by-reference are called "var parameters". In the procedure setToNil below, please note the keyword 'var' which precedes the parameter 'ptr'. When a pointer is passed to this procedure, it will be passed by reference. Note the behavior: when this procedure sets ptr to nil (that's pascal speak for NULL), it will set the argument to nil--you can't do that in Java.

program passByRefDemo;
type 
   iptr = ^integer;
var
   ptr: iptr;

   procedure setToNil(var ptr : iptr);
   begin
       ptr := nil;
   end;

begin
   new(ptr);
   ptr^ := 10;
   setToNil(ptr);
   if (ptr = nil) then
       writeln('ptr seems to be nil');     { ptr should be nil, so this line will run. }
end.

EDIT 2

Some excerpts from "THE Java Programming Language" by Ken Arnold, James Gosling (the guy who invented Java), and David Holmes, chapter 2, section 2.6.5

All parameters to methods are passed "by value". In other words, values of parameter variables in a method are copies of the invoker specified as arguments.

He goes on to make the same point regarding objects . . .

You should note that when the parameter is an object reference, it is the object reference-not the object itself-that is passed "by value".

And towards the end of the same section he makes a broader statement about java being only pass by value and never pass by reference.

The Java programming language does not pass objects by reference; it passes object references by value. Because two copies of the same reference refer to the same actual object, changes made through one reference variable are visible through the other. There is exactly one parameter passing mode-pass by value-and that helps keep things simple.

This section of the book has a great explanation of parameter passing in Java and of the distinction between pass-by-reference and pass-by-value and it's by the creator of Java. I would encourage anyone to read it, especially if you're still not convinced.

I think the difference between the two models is very subtle and unless you've done programming where you actually used pass-by-reference, it's easy to miss where two models differ.

I hope this settles the debate, but probably won't.

EDIT 3

I might be a little obsessed with this post. Probably because I feel that the makers of Java inadvertently spread misinformation. If instead of using the word "reference" for pointers they had used something else, say dingleberry, there would've been no problem. You could say, "Java passes dingleberries by value and not by reference", and nobody would be confused. (Hence forth, when referencing pass by reference vs value, I shall refer to references as dinglebarries.)

That's the reason only Java developers have issue with this. They look at the word "reference" and think they know exactly what that means, so they don't even bother to consider the opposing argument.

Anyway, I noticed a comment by dhackner in an older post, who made a balloon analogy which I really liked. So much so that I decided to glue together some clip-art to make a set of cartoons to illustrate the point.

Passing a reference by value--Changes to the reference are not reflected in the caller's scope, but the changes to the object are. This is because the reference is copied, but the both the original and the copy refer to the same object. Passing Object references By Value

Pass by reference--There is no copy of the reference. Single reference is shared by both the caller and the function being called. Any changes to the reference or the Object's data are reflected in the caller's scope. Pass by reference

EDIT 4

I have seen posts on this topic which describe the low level implementation of parameter passing in Java, which I think is great and very helpful because it makes an abstract idea concrete. However, to me the question is more about the behavior described in the language specification than about the technical implementation of the behavior. This is an exerpt from the Java Language Specification, section 8.4.1 :

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.

Which means, java creates a copy of the passed parameters before executing a method. Like most people who took compilers in college I used "The Dragon Book" which is THE compilers book. It has a good description of "Call-by-value" and "Call-by-Reference" in Chapter 1. The Call-by-value description matches up with Java Specs exactly.

When I took compilers, I used the first edition of the book from 1986 which pre-dated Java by about 9 or 10 years. However, I just ran across a copy of the 2nd Eddition from 2007 which actually mentions Java! Section 1.6.6 labeled "Parameter Passing Mechanisms" describes parameter passing pretty nicely. Here is an excerpt under the heading "Call-by-value" which mentions Java:

In call-by-value, the actual parameter is evaluated (if it is an expression) or copied (if it is a variable). The value is placed in the location belonging to the corresponding formal parameter of the called procedure. This method is used in C and Java, and is a common option in C++ , as well as in most other languages.

@user207421 2019-01-25 21:43:37

Java does not allow us to 'emulate pass by reference'. The failure of one user to accept an answer is not a huge weakness of the entire site.

@Sanjeev 2019-01-25 22:02:42

Explain what you mean by "java does not allow us to emulate'. As far as the weakness, it's a difference in opinion.

@Scuba Steve 2019-02-04 22:51:33

Honestly, you can simplify this answer by saying Java is pass by value only for primitive types. Everything that inherits from Object is effectively pass by reference, where the reference is the pointer you're passing.

@Sanjeev 2019-02-06 00:19:57

@Scuba Steve if that's what you got out of my post, I have totally failed to get my message across. Everything in java is ALWAYS pass by value and NEVER pass by reference. When passing an object, you're actually passing a reference to that object, but THE REFERENCE IS BEING PASSED BY VALUE (i.e. a copy of the reference is passed.) And again, this not my personal opinion, but true by definition.

@Scuba Steve 2019-02-06 00:36:22

That's true for any reference in any language... unless you explicitly passed a reference by reference, which generally speaking, wouldn't make much sense to do.

@Sanjeev 2019-02-06 00:40:23

Not the case. This is true in C, Java, JavaScript, but not true in Pascal (which has "Variable Parameters" the same as reference parameters) and C++ (please see the example I posted)

@Sanjeev 2019-02-06 00:49:36

Other examples of pass by reference languages are c#, php, vb.net, and fortran.

@Juan Mendes 2019-04-16 15:15:59

I don't think C++ owns the term "pass by reference". In Java, it's very common to say "pass a reference", because when you pass an object, you don't copy the object, as you could in C++. it is a pointer to a location in memory, but yes a new pointer. In C++, it's a pointer to a pointer... So, I prefer to use other terms and not assume C++ is the standard everyone must follow and understand.

@Sanjeev 2019-04-17 03:32:23

@JuanMendes, I just used C++ as an example; I could give you examples in other languages. The term "Pass by reference" existed long before C++ existed. It's a textbook term with a very specific definition. And by definition, Java is not pass by reference. You can keep using the term in this way if you'd like, but your usage will not be consistent with the textbook definition. It's not just a pointer to a pointer. It's a construct provided by the language to allow "Pass By Reference". Please take a close look at my example, but please don't take my word for it and look it up for yourself.

@AutomatedMike 2019-05-03 12:20:06

Describing java as "pass-by-value" is highly misleading. For non-primitive types Java uses pass by value of the reference. Pass by value implies the value is copied when passed to a method. It is not, the reference is copied. What java does is not the same as either pass by value or pass by reference in C++.

@Sanjeev 2019-05-05 21:12:06

@AutomatedMike, if the reference was being passed-by-reference, there wouldn't be a copy of the the reference. It would be as if the argument and parameter were two different names for the same variable. That's the distinction between pass-by-value and pass-by-reference. Please take a look at my c++ example to see what I mean. Another way to look at it is that java does not pass the "Swap Test". Here is a great article which discusses exactly what I mean : javapapers.com/core-java/…. An example Pascal would be more clear. I'll try and post one.

@Jędrzej Dudkiewicz 2019-06-13 10:29:39

@AutomatedMike I think that describing Java as "pass-by-reference" is also misleading, their reference are nothing more than pointers. As Sanjeev wrote value, reference and pointer are textbook terms that have their own meaning regardless of what Java creators use.

@Sanjeev 2019-06-19 21:53:10

@dhackner, Thanks for the balloon idea.

@AutomatedMike 2019-06-25 09:43:21

@Sanjeev that's why I said "pass by value of the reference" not pass-by-reference or pass-by-value, as stated many times both these terms are miss-leading when describing what java does.

@Sanjeev 2019-06-25 12:27:24

@AutomatedMike, I understand where you're going with that. My point is that we don't need new terminology. Pass-by-value adequately describes what java does. The value of the reference is indeed passed by value in Java.

@Victor 2019-07-19 12:39:42

@Sanjeev thanks for sharing!, the example with the ballons is super practical!

@Sanjeev 2019-07-19 15:45:48

@Victor thanks! Glad you found it useful.

@Artanis Zeratul 2019-08-17 21:54:21

Java is pass by reference. Or passing the value of a reference in objects. Since in Java everything is an object except for atomic types like int, char, boolean, etc. For people who always says its pass by value I think they making it more complicated rather than simplifying the matter.

@Sanjeev 2019-08-18 20:10:49

@ArtanisZeratul the point is subtle, but not complicated. Please take a look at the cartoon I posted. I felt it was pretty simple to follow. That Java is Pass-by-value isn't just an opinion. It's true by textbook definition of pass-by-value. Also, "people who always say it's pass by value" include computer scientists like James Gosling, the creator of Java. Please see the quotes from his book under "Edit 2" in my post.

@newfolder 2019-09-03 17:06:56

What a great answer, "pass by reference" does not exist in java(and other languages like JS).

@Rose 2019-09-21 08:09:07

I think this simple explanation might help you understand as I wanted to understand this same thing when I was struggling through this.

When you pass a primitive data to a function call it's content is being copied to the function's argument and when you pass an object it's reference is being copied to the function's argument. Speaking of object, you can't change the copied reference-the argument variable is referencing to in the calling function.

Consider this simple example, String is an object in java and when you change the content of a string the reference variable will now point to some new reference as String objects are immutable in java.

String name="Mehrose";  // name referencing to 100

ChangeContenet(String name){
 name="Michael"; // refernce has changed to 1001

} 
System.out.print(name);  //displays Mehrose

Fairly simple because as I mentioned you are not allowed to change the copied reference in the calling function. But the problem is with the array when you pass an array of String/Object. Let us see.

String names[]={"Mehrose","Michael"};

changeContent(String[] names){
  names[0]="Rose";
  names[1]="Janet"

}

System.out.println(Arrays.toString(names)); //displays [Rose,Janet]

As we said that we can't change the copied reference in the function call and we also have seen in the case of a single String object. The reason is names[] variable referencing to let's say 200 and names[0] referencing to 205 and so on. You see we didn't change the names[] reference it still points to the old same reference still after the function call but now names[0] and names[1] reference has been changed. We Still stand on our definition that we can't change the reference variable's reference so we didn't.

The same thing happens when you pass a Student object to a method and you are still able to change the Student name or other attributes, the point is we are not changing the actual Student object rather we are changing the contents of it

You can't do this

Student student1= new Student("Mehrose");

changeContent(Student Obj){
 obj= new Student("Michael") //invalid
 obj.setName("Michael")  //valid

}

@natwar kumar 2019-07-27 03:56:02

public class Test {

    static class Dog {
        String name;

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Dog other = (Dog) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            return true;
        }

        public String getName() {
            return name;
        }

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

        Dog(String sd) {
            this.name = sd;
        }
    }
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        Dog aDog = new Dog("Max");

        // we pass the object to foo
        foo(aDog);
        Dog oldDog = aDog;

        System.out.println(" 1: " + aDog.getName().equals("Max")); // false
        System.out.println(" 2 " + aDog.getName().equals("huahua")); // false
        System.out.println(" 3 " + aDog.getName().equals("moron")); // true
        System.out.println(" 4 " + " " + (aDog == oldDog)); // true

        // part2
        Dog aDog1 = new Dog("Max");

        foo(aDog1, 5);
        Dog oldDog1 = aDog;

        System.out.println(" 5 : " + aDog1.getName().equals("huahua")); // true
        System.out.println(" part2 : " + (aDog1 == oldDog1)); // false

        Dog oldDog2 = foo(aDog1, 5, 6);
        System.out.println(" 6 " + (aDog1 == oldDog2)); // true
        System.out.println(" 7 " + (aDog1 == oldDog)); // false
        System.out.println(" 8 " + (aDog == oldDog2)); // false
    }

    /**
     * 
     * @param d
     */
    public static void foo(Dog d) {
        System.out.println(d.getName().equals("Max")); // true

        d.setName("moron");

        d = new Dog("huahua");
        System.out.println(" -:-  " + d.getName().equals("huahua")); // true
    }

    /**
     * 
     * @param d
     * @param a
     */
    public static void foo(Dog d, int a) {
        d.getName().equals("Max"); // true

        d.setName("huahua");
    }

    /**
     * 
     * @param d
     * @param a
     * @param b
     * @return
     */
    public static Dog foo(Dog d, int a, int b) {
        d.getName().equals("Max"); // true
        d.setName("huahua");
        return d;
    }
}

The sample code to demonstrate the impact of changes to the object at different functions .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Java is a call by value

How it works

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

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

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

@grindlewald 2019-08-22 19:47:09

First let's understand Memory allocation in Java: Stack and Heap are part of Memory that JVM allocates for different purposes. The stack memory is pre-allocated to thread, when it is created, therefore, a thread cannot access the Stack of other thread. But Heap is available to all threads in a program.

For a thread, Stack stores all local data, metadata of program, primitive type data and object reference. And, Heap is responsible for storage of actual object.

Book book = new Book("Effective Java");

In the above example, the reference variable is "book" which is stored in stack. The instance created by new operator -> new Book("Effective Java") is stored in Heap. The ref variable "book" has address of the object allocated in Heap. Let's say the address is 1001.

enter image description here

Consider passing a primitive data type i.e. int, float, double etc.

public class PrimitiveTypeExample { 
    public static void main(string[] args) {
       int num = 10;
       System.out.println("Value before calling method: " + num);
       printNum(num);
       System.out.println("Value after calling method: " + num);
    }
    public static void printNum(int num){
       num = num + 10;
       System.out.println("Value inside printNum method: " + num);
    }
}

Output is: Value before calling method: 10 Value inside printNum method: 20 Value after calling method: 10

int num =10; -> this allocates the memory for "int" in Stack of the running thread, because, it is a primitive type. Now when printNum(..) is called, a private stack is created within the same thread. When "num" is passed to this method, a copy of "num" is created in the method stack frame. num = num+10; -> this adds 10 and modifies the the int variable within the method stack frame. Therefore, the original num outside the method stack frame remains unchanged.

Consider, the example of passing the object of a custom class as an argument.

enter image description here

In the above example, ref variable "book" resides in stack of thread executing the program, and the object of class Book is created in Heap space when program executes new Book(). This memory location in Heap is referred by "book". When "book" is passed as method argument, a copy of "book" is created in private stack frame of method within the same stack of thread. Therefore, the copied reference variable points to the same object of class "Book" in the Heap.

enter image description here

The reference variable within method stack frame sets a new value to same object. Therefore, it is reflected when original ref variable "book" gets its value. Note that in case of passing reference variable, if it is initialized again in called method, it then points to new memory location and any operation does not affect the previous object in the Heap.

Therefore, when anything is passed as method argument, it is always the Stack entity - either primitive or reference variable. We never pass something that is stored in Heap. Hence, in Java, we always pass the value in the stack, and it is pass by value.

@Amit Sharma 2019-07-17 05:10:43

Java passes parameters by value, There is no option of passing a reference in Java.

But at the complier binding level layer, It uses reference internally not exposed to the user.

It is essential as it saves a lot of memory and improves speed.

@SamB 2019-09-11 18:41:02

What is this "uses references internally" bit talking about???

@user10356724 2019-06-18 10:15:03

I disagree that Java is only pass by value. Let us see this code snippet

import java.util.ArrayList;
public class Main {
    public static void getList(ArrayList<String> list){
        list.add("Hello") ;
    }
    public static void main(String[] args) {
        ArrayList<String> list=new ArrayList();
        System.out.println(list);
        getList(list);
        System.out.println(list);
    }
}

The output

[]
[Hello]

if JAVA had been call by value then why would my list be changed after calling the function the function should have changed only a copy of variable and the original list would have remained same

@Minn 2019-06-18 13:51:55

Here you have to understand the difference between a shallow copy and a deep copy. The reference is passed by value, its a shallow copy since the referenced value is not copied. stackoverflow.com/questions/184710/…

@user10356724 2019-06-18 14:03:09

So what i have done is shallow copy . It does not create new objects and hence it is kind of pass by value stackoverflow.com/questions/1175620/…

@Minn 2019-06-18 15:02:20

What you have done emulates pass-by-reference through an indirect reference. This is comparable to passing a pointer by value in C.

@user10356724 2019-06-18 15:05:54

It allll makes sense now

@Sanjeev 2019-06-19 18:35:22

@who If you were passing "list" by-reference to the method getList(), you'd be able to set "list" to null or assign a new object to "list" and the change would be reflected in main(). You're not really passing "list" by reference. You are passing a reference to "list" by value.

@user10356724 2019-06-20 03:42:29

@Sanjeev but i assigned "hello" to the empty list did not i

@Sanjeev 2019-06-20 04:19:38

Yes, but by definition, that's not enough to qualify as pass-by-reference. As @Minn mentioned, that's only emulated pass-by-reference. True pass-by-reference would allow you to change the value of the "reference", not just the object it points to. In fact the object is not in question at all since the "reference" is what's being passed to the function. To quote Gosling (the inventor of Java): "The Java programming language does not pass objects by reference; it passes object references by value." -- James Gosling, THE Java Programming Language, Chapter 2, Section 2.6.5

@user10356724 2019-06-20 06:01:20

@Sanjeev i am only a beginner so thank you for your clarification sir

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

Unlike some other languages, Java does not allow you to choose between pass-by-value and 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

@Stephane 2019-08-06 11:32:43

If you use a reference-type parameter to modify its referenced object then the caller's referenced object has been changed, it's pass by reference :-)

@moldovean 2019-04-30 14:50:45

Long story short:

  1. Non-primitives: Java passes the Value of the Reference.
  2. Primitives: just value.

The End.

(2) is too easy. Now if you want to think of what (1) implies, imagine you have a class Apple:

class Apple {
    private double weight;
    public Apple(double weight) {
        this.weight = weight;
    }
    // getters and setters ...

}

then when you pass an instance of this class to the main method:

class Main {
    public static void main(String[] args) {
        Apple apple = new Apple(3.14);
        transmogrify(apple);
        System.out.println(apple.getWeight()+ " the goose drank wine...";

    }

    private static void transmogrify(Apple apple) {
        // does something with apple ...
        apple.setWeight(apple.getWeight()+0.55);
    }
}

oh.. but you probably know that, you're interested in what happens when you do something like this:

class Main {
    public static void main(String[] args) {
        Apple apple = new Apple(3.14);
        transmogrify(apple);
        System.out.println("Who ate my: "+apple.getWeight()); // will it still be 3.14? 

    }

    private static void transmogrify(Apple apple) {
        // assign a new apple to the reference passed...
        apple = new Apple(2.71);
    }


}

@Philip Rego 2019-06-18 16:57:00

Upvote for showing how it actually works without using ambiguous language.

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

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

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

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

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

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

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

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

Pass by value example 1

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

public class Test
{
    public static void main(String args)
    {
        int[] array1 = { 1, 10, -7 };

        reverseArray(array1);
    }

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

Pass by value example 2

So, if we say

array1[0] = 5;

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

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

array1 = array2;

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

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

return array2; // This code is in reverseArray method.

So lets write all the things we have done at once now.

public class Test
{
    public static void main(String args)
    {
        int[] array1 = { 1, 10, -7 };
        int[] array2 = { 5, -190, 0 };

        array1 = reverseArray(array1); /* array1 of 
         main starts pointing to c instead of a */
    }

    public void reverseArray(Int[] array1)
    {
        int[] array2 = { -7, 0, -1 };

        array1[0] = 5; // array a becomes 5, 10, -7

        array1 = array2; /* array1 of reverseArray starts
          pointing to c instead of a (not shown in image below) */
        return array2;
    }
}

enter image description here

And now that reverseArray method is over, its reference variables(array1 and array2) are gone. Which means we now only have the two reference variables in main method array1 and array2 which point to c and b arrays respectively. No reference variable is pointing to object (array) a. So it is eligible for garbage collection.

You could also assign value of array2 in main to array1. array1 would start pointing to b.

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

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

package com.asok.cop.example.task;
public class Example {
    int data = 50;

    void change(int data) {
        data = data + 100;// changes will be in the local variable 
        System.out.println("after add " + data);
        }

    public static void main(String args[]) {
        Example op = new Example();
        System.out.println("before change " + op.data);
        op.change(500);
        System.out.println("after change " + op.data);
    }
}

Output:

before change 50
after add 600
after change 50

as Michael says in the comments:

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

@AutomatedMike 2019-05-03 12:18:06

Describing java as "pass-by-value" is highly misleading. For non-primitive types Java uses "pass by value of the reference". "Pass by value" implies the value is copied when passed to a method. It is not, the reference is copied.

@Stephane 2019-04-24 13:37:28

This above article is confusing.

It assumes making a copy of the reference and passing it to the method is a pass by value, because a copy is passed. That is not what I and many understand.

Is the language passing by value or by reference ? Why do we ask this question ?

The whole issue occurs when calling a method. Such a method is defined with parameters and is called with arguments.

Making the distinction between parameter and argument is helpful. The parameter is the name of the received thing specified when defining the method. The argument is the name of the sent thing specified when calling the method.

Any content stored in memory has an address so as to be accessed. This content address is called a reference. With the reference it is possible to access the content. If the reference is given to a tier then this tier can access and update the referenced content. If the reference is given to a method, then this method can also access and update this referenced content.

What happens when "passing" an argument into a method parameter ? A copy of the argument is made and given to the method parameter.

What do we understand when we say "pass by value" and "pass by reference" ? When using the word "value" we understand the actual content being stored, say someone's name. When using the word "reference" we understand a memory address pointing to a "value".

So, when we say "pass by value" we understand that the argument we pass into the method parameter is some content. And when we say "pass by reference" we understand that the argument we pass into the method parameter is a memory address pointing to some content.

If what is passed is some content, then a copy of this content is being made and given to the method. Since the content given is a copy, there is no risk of altering the original content.

If, on the other hand, what is passed is a reference to some content, then a copy of this reference is being made and given to the method, with the referenced content itself not being a copy of the original content, but being the original content, only its reference having been copied.

In Java, I understand that a primitive type is passed as content, that is, is passed by value, and an object is passed as a reference to some content, that is, is passed by reference.

That a copy of the reference is made before being given to the method parameter, does not make this reference a value.

The swap test is not a decisive indicator.

If an object outside a method can be altered from within the method when passing it to the method, then the passing is by reference.

The Java documentation and lots of articles are at best confusing on this, and at worst, wrong.

My two cents.

@Rodrigo Rodrigues 2019-10-09 04:56:45

Wrong. Try to use a language that actually passes arguments by reference, like Fortran, and you will see the difference.

@OverCoder 2016-04-25 14:32:28

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)

@Rodriguez David 2019-01-23 22:00:46

Very simple! A variable will be passed by value if it's a primitive and by reference if it's an object.

That's all

@Captain Man 2019-01-24 22:18:08

This is wrong. As a lot of the comments and answers explain, it is confusing because in Java objects use references. However, the phrase "pass by reference" means something specific. "Pass by value" means the thing going to the method is copied -- a whole new thing. "Pass by reference" means the thing going to the method is shared between both places. Java is always always always "pass by value." When you send an object, it copies the reference, but that doesn't make it "pass by reference".

@Faisal Shaikh 2019-03-27 09:27:34

Your answer making some sense. I don't know why people downvoted this question.

@Sanjeev 2019-05-06 20:08:25

Your answer makes no sense. I know why people downvoted this answer.

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

Java always passes arguments by value NOT by reference.


Let me explain this through an example:

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

I will explain this in steps:

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

    Foo f = new Foo("f");
    

    enter image description here

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

    public static void changeReference(Foo a)
    

    enter image description here

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

    changeReference(f);
    

    enter image description here

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

    Foo b = new Foo("b");
    

    enter image description here

  5. a = b makes a new assignment to the reference a, not f, of the object whose its attribute is "b".

    enter image description here


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

    enter image description here

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

    enter image description here

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

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

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

@0x6C38 2013-07-15 19:08:28

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

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

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

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

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

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

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

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

@MikeBraun oh I see, I misunderstood when you said " BUT IT DID NOT CHANGE 'f'". I thought you also meant the object 'f' points to does not change.

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

If I say that object in Java is passed to a method by copy of the reference, that would probably solve the whole discussion. Nice diagrams above would fit-in and support that statement.

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

The setAttribute method need to be accessed by Java reflection. tutorials.jenkov.com/java-reflection/…

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

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

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

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

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

I am a little confused on line 5. I thought it goes from right to left; meaning object a is assigned object b and not the other way around. Or simply whatever the value of a is now whatever the value of b. Am I correct?

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

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

@Aadam 2019-02-03 14:41:29

Well explained. Now i can say yes. The parameter name is used to point at different locations. So its paas by value 😉

@AutomatedMike 2019-05-03 12:22:06

Describing java as "pass-by-value" is highly misleading. For non-primitive types Java uses pass by value of the reference. Pass by value implies the value is copied when passed to a method. It is not, the reference is copied.

@Philip Rego 2019-06-13 14:58:18

3 is describing pass by reference. Fix the answer.

@Tom O. 2019-08-02 15:43:29

Fantastic explanation with supplementary charts to solidify understanding. Nice!

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

Java is always pass-by-value. Unfortunately, when we pass the value of an object, we are passing the reference to it. This is confusing to beginners.

It goes like this:

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

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

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

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

Likewise:

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

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

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

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

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

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

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

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

beware however that integral types are passed by value and not by reference. Also immutable types are passed by reference but "kinda" works as passing them by value: the most common example would be String. This allow for internal space optimization of immutable objects.

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

@Lorenzo: No, in Java everything is passed by value. Primitives are passed by value, and object references are passed by value. The objects themselves are never passed to a method, but the objects are always in the heap and only a reference to the object is passed to the method.

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

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

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

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

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

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

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

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

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

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

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

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

@Marsellus Wallace 2011-08-12 01:31:43

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@Bill Rosmus 2012-08-30 05:54:16

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

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

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

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

Basically a java reference passed as a function parameter is like a C++ pointer passed as a function parameter (not pass-by-reference; C++ convention of by-reference), when you modify it inside the function, you are modifying a local variable, neither the referenced object, nor the passed reference ..

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

Really its a dilemma in the terminology. Consider the same example in terms of c++, for which everybody hopefully agree its 'passed by reference' (or its reference passed by value?) void foo(Dog & d) { 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 }

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

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

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

@BillR Incredible that despite the utterly clear answer you're still arguing against it. Java passes only pointers. A pointer is an opaque type that we can think of as being a primitive number. This number is passed by value. So Java passes pointers, and those pointers are pass by value.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@Shawn Java does not behave like the C++ func(Dog &d). If you reassign d in the body of the function func(Dog &d), the object that was used to call the function will also be reassigned. It behaves more like func(Dog *d). If you reassign the pointer in the body of the function, the original pointer passed to the function won't be reassigned.

@PC Luddite 2015-08-31 20:20:50

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

@izb the fact that pointers to objects are copied is different from the notion that objects are passed by reference. Because they are not passed by reference, their reference is copied.

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

This can cause SERIOUS problems. Because when you pass an object as parameter in a function, you don't know wether it will be modified by the user who use the function.

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

I would suggest to avoid using those terms altogether within a Java context. Just known how it really works in Java — this example did a great job doing so.

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

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

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

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

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

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

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

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

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

@peter no, that is not correct. That is passing a copy of a pointer to a selectively mutable memory location. Mutating the value stored there is a side effecting operation that is observable to both the caller and the callee.

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

Java is "pass-by-voodoo-doll", when an object is passed while calling a method, the method actually receives a voodoo-doll using which you can control the actual object, but can't replace the object altogether.

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

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

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

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

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

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

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

Great explanation!!! I would add that in case of Java RMI calls, the method receives a full serialized copy of the parameter, not the value of the reference.

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

"When we pass the value of an object, we are passing the reference to it." Then, Java is a pass-by-reference language, I think...

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

Then why even have the two god damn terms? Yes, pass-by-reference will deal with values at some level but you don't have to abstract concepts to the n-th degree!

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

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

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

All this debate is actually because guys at Sun made a terrible naming mistake. They used the name REFERENCE instead of POINTERS. Well it was not actually a mistake. Acording to a guy, who worked with another guy from the original Sun team, the usage of reference word instead of pointers was requested by the sale department. The sale department wanted to push Java as a secure language, and one of the strong point they where advertising was "Java's advantages that it does not allow pointer arithmetic as C++ does".

@Grigore Madalin 2017-11-12 08:01:34

The guy knwon by my guy, like the rest of the Sun team had to create this big lie. They knew what pointers are. They new what references are. But the money demanded the terms switch. Because of this, today many Java programmers don't have a clue what a reference is because they learned the wrong term. Originally a "reference" strictly means an alias to a variable passed as a parameter. The reference word describe the method of passing a parameter to a function. Sun team redefined the "reference" term because Sun wanted more success for the Java language and more money in the pocket.

@Grigore Madalin 2017-11-12 08:08:41

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

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

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

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

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

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

As this answer points out "passing by reference" is different than "passing a reference" (which can still be done in a pass-by-value language like Java). A lot of commenters have failed to grasp the difference.

@ikegami 2018-03-30 09:28:17

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

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

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

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

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

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

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

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

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

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

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

@spicypumpkin 2018-09-12 17:23:19

@Giacomo As the answer says, the function takes a reference to the value, so you can update the original value. But the variable that holds this reference has no connection to the variable outside of the function that refers to the same value. So when you assign a new value to the local variable inside the function, you simply overwrite whatever reference was passed to.

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

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

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

@Aaron The problem is that there is a confusion. As the examples show, the two passes show different behaviors that imho they require different definitions. Clearly, these "English words" aren't accurate enough to define these schemes.

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

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

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

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

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

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

@AutomatedMike 2019-05-03 12:22:29

Describing java as "pass-by-value" is highly misleading. For non-primitive types Java uses pass by value of the reference. Pass by value implies the value is copied when passed to a method. It is not, the reference is copied.

@Sanjeev 2019-05-07 17:06:22

@BillRosmus - I know this is an old post, but felt compelled to reply to you. Please look at these C++ function headers : int A(char x), int B(char *x), int C(char &x), and int D(char *&x). The functions A and B pass a variable and a pointer, BY-VALUE. The functions C and D pass a variable and and a pointer, BY-REFERENCE. Neither Java nor C-programming allow what the functions C and D can do. The distinction is subtle but important.

@Zhang 2019-05-30 08:50:49

I see. Java passes a pointer, nether a reference nor a value.

@Geronimo 2019-06-26 06:05:54

It took more than a decade but I think @Zhang finally summed it up: pass-by-pointer, I hope the sales department at Sun will forgive us.

@Kaushal28 2019-07-16 16:08:01

This should be added into documentations

@Bruce 2019-08-13 05:34:58

"when we pass the value of an object" -> Don't you mean "when we pass the value of a variable that refers to an object" or perhaps "when we pass an object"?

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

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

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

public void foo(Object param)
{
  // some code in foo...
}

public void bar()
{
  Object obj = new Object();

  foo(obj);
}

is exactly the same as...

public void bar()
{
  Object obj = new Object();

  Object param = obj;

  // some code in foo...
}

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

So, in fact, what we're looking for in Java is how variable assignment works. I found it in the docs :

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

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

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

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

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

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

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

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

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

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

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

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

    height.value = width.value;

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

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

    height.value = 9;

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

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

    height = width;

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

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

    height.value = 9;

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

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

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

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

This is the output of my run:

Assignment operator evaluation using two MyInteger objects named height and width

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

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

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

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

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

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

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

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

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

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

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

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

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

Easy answer for beginner

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

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

Example (not a Dog) :

public class HelloWorld {
    private Integer i;
    private String s;
    private Boolean b;

    public static void main(String[] args) {
        HelloWorld h = new HelloWorld();

        h.s = "Bill";
        h.ModMe(h.s);
        h.i = 2;
        h.ModMe(h.i);
        h.b = true;
        h.ModMe(h.b);
        System.out.println(h.s + " " + h.i + " " + h.b);

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

        String test = "TEST";
        h.ModMe(test);
        System.out.println(test);
    }

    public void ModMe(Object o) {
        if (o instanceof HelloWorld) {
            ((HelloWorld) o).i = (int) Math.pow(((HelloWorld) o).i, 2);
            ((HelloWorld) o).b = !((HelloWorld) o).b;
            ((HelloWorld) o).s = ((HelloWorld) o).s.concat(" modded successfully");
        } else if (o instanceof Integer) {
            o = (Integer) o + (Integer) o;
        } else if (o instanceof String) {
            o = ((String) o).concat(" is modified.");
        } else if (o instanceof Boolean) {
            o = !(Boolean) o;
        }
    }
}

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

@Sanjeev 2019-05-06 19:45:48

Passing a reference is not the same as pass-by-reference. Java is ALWAYS pass-by-value. This is true even when passing a reference because the reference is being passed by value (i.e. a copy of the reference is being passed). This is confusing in Java due to the word "reference" in Java to refer to a pointer.

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

Java passes primitive types by value and class types by reference

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

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

In my book that's called passing by reference.

Brian Bi - Which programming languages are pass by reference?

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

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

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

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

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

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

@Sanjeev 2019-01-23 00:01:56

It's not about what's "In your book." "Pass by reference" and "Pass by value" are industry standard terms which have very specific definitions. By those definitions Java is "Pass by value" without exceptions.

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

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

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

public static void main(String[] args) {
    String baz = "Hah!";
    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.

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

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

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

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

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

Java is always pass by value, not pass by reference

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

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

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

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

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

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

class Test {
    String name;
}

The output of this program is:

changevalue

Let's understand step by step:

Test t = new Test();

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

first illustration

new PassByValue().changeValue(t);

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

second illustration

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

To understand this more clearly, consider the following example:

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

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

class Test {
    String name;
}

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

third illustration

Hopefully this will help.

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

PT 1: Of Realty Listings

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

TL;DR: Minimal example:

package foobar;
import java.util.ArrayList;

public class FooBar {

  public static void main(String[] args) {
    ArrayList<Integer> list1 = new ArrayList<>(); // An object.
    list1.add(1);

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

    int x = 42; // A primitive (same with Integer).

    sideEffects(list1, list2, x);

    System.out.println(list1); // Output: [1]     (unchanged)
    System.out.println(list2); // Output: [2, 3]  (changed !)
    System.out.println(x);     // Output: 42      (not changed)
  }

  private static void sideEffects(ArrayList<Integer> list1, ArrayList<Integer> list2, int x) {
    list1 = list2;
    list1.add(3);
    x = 21;
  }
}

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

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

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

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

Colloquially called a pointer.

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

@Gevorg - Then what is a "NullPointerException"?

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

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

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

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

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

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

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

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

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

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

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

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

results in this:

primitives on the stack

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

Like so:

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

a b*7ch aint one!

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

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

marx brothers

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

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

public static void main(String[] args){
    String hisName = "John J. Jingleheimerschmitz";
    String myName = hisName;
    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".

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

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

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

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

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

That's not correct @cHao. Java does not place any live objects on the stack. It may be an "implementation detail" in that it's not specifically outline in the Java spec, but that fact is that all Java implementations place all objects in the heap.

@cutmancometh 2013-12-18 09:22:57

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

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

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

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

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

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

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

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

It has nothing to do with stack vs heap allocation. It has to do with indirection. Stack locations have addresses. At any rate, Java passes all arguments by value.

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

This answer is just wrong. Both references and primitives can be found on either the stack or the heap. And which it is is entirely irrelevant to the whole "pass by reference" vs "pass by value" issue. Your references and your primitives get passed by value, regardless of whether they live on the heap or the stack.

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

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

@cutmancometh 2017-01-25 18:31:46

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

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

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

@Faraz 2017-03-25 20:38:02

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

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

Sure, can you be more specific? Could post post the code you're referring to in 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.

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

@cutmancometh if it is a stupid argument, how can we describe the distinction? It exists in other languages. It is significant to Java in that other languages share a largely common call syntax. Consider C#'s ref.

@Marsellus Wallace 2011-08-12 01:22:19

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

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

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

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

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

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

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

1. Person person;
2. person = new Person("Tom");
3. changeName(person);
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!

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

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

@Marsellus Wallace 2012-02-25 21:25:22

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

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

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

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

when two objects refer to the same object, does that means it will occupy more memory in terms of an actual value? Or it will just occupy the memory for creating a pointer to the same place in memory? How does it work?

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

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

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

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

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

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

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

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

@Aquarelle 2014-01-18 23:23:10

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

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

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

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

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

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

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

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

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

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

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

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

I have read numerous articles on this mess by Sun nomenclature, but this is the only one that is readable, entertaining and clearly understandable. Thank you !

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

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

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

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

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

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

public class Balloon {

    private String color;

    public Balloon(){}

    public Balloon(String c){
        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.

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

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

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

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

Example using primitive data type:

public class PassByValuePrimitive {
    public static void main(String[] args) {
        int i=5;
        System.out.println(i);  //prints 5
        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
    }
}

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

Java is strictly passed by value

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

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

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

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

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

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

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

Hence Java strictly use pass by value mechanism

Related Questions

Sponsored Content

28 Answered Questions

[SOLVED] How do I determine whether an array contains a particular value in Java?

  • 2009-07-15 00:03:21
  • Mike Sickler
  • 1868309 View
  • 2173 Score
  • 28 Answer
  • Tags:   java arrays

65 Answered Questions

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

  • 2008-12-12 18:20:57
  • user42155
  • 3878167 View
  • 3333 Score
  • 65 Answer
  • Tags:   java random integer

55 Answered Questions

[SOLVED] Creating a memory leak with Java

58 Answered Questions

[SOLVED] How do I read / convert an InputStream into a String in Java?

20 Answered Questions

[SOLVED] Does Java support default parameter values?

29 Answered Questions

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

26 Answered Questions

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

  • 2009-03-02 22:56:34
  • Malachi
  • 1044558 View
  • 1872 Score
  • 26 Answer
  • Tags:   java enums

26 Answered Questions

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

15 Answered Questions

4 Answered Questions

[SOLVED] Javascript by reference vs. by value

Sponsored Content