Does Java pass by reference or by value?




Java passes everything by value, and not by reference – make sure you remember that. And when we say everything, we mean everything – objects, arrays (which are objects in Java), primitive types (like ints and floats), etc. – these are all passed by value in Java. What is the difference between pass by value and pass by reference? When passing an argument (or even multiple arguments) to a method, Java will create a copy or copies of the values inside the original variable(s) and pass that to the method as arguments – and that is why it is called pass by value. The key with pass by value is that the method will not receive the actual variable that is being passed – but just a copy of the value being stored inside the variable. So, how does this affect the code you write? Well, this is best illustrated by a simple and easy to understand example.

Example of pass by value in Java

Suppose we have a method that is named “Receiving” and it expects an integer to be passed to it:

public void Receiving (int var)
{
  var = var + 2;
}

Note that the “var” variable has 2 added to it. Now, suppose that we have some code which calls the method Receiving:

public static void main(String [] args)
{
  int passing = 3;

  Receiving (passing);
 
  System.out.println("The value of passing is: " + passing);
}

In the main method, we set the variable “passing” to 3, and then pass that variable to the Receiving method, which then adds 2 to the variable passed in.

What do you think the “System.out.println” call will print out? Well, if you thought it would print out a “5” you are wrong. It will actually print out a “3”. Why does it print out a 3 when we clearly added a 2 to the value in the Receiving method?

The reason it prints out a “3” is because Java passes arguments by value – which means that when the call to “Receiving” is made, Java will just create a copy of the “passing” variable and that copy is what gets passed to the Receiving method – and not the original variable stored in the “main” method. This is why whatever happens to “var” inside the Receiving method does not affect the “passing” variable inside the main method.

How does pass by value work?

Java basically creates another integer variable with the value of 3, and passes that to the “Receiving” method. That is why it is called “pass by value” – because the value of 3 is what is being passed to the “Receiving” method, not a reference to the “passing” variable.

Are objects passed by reference in Java?




As we said in the beginning of this article – everything is passed by value in Java. So, objects are not passed by reference in Java. Let’s be a little bit more specific by what we mean here: objects are passed by reference – meaning that a reference/memory address is passed when an object is assigned to another – BUT (and this is what’s important) that reference is actually passed by value. The reference is passed by value because a copy of the reference value is created and passed into the other object – read this entire article and this will make a lot more sense. So objects are still passed by value in Java, just like everything else.

One other very important thing to know is that a variable of a class type stores an address of the object, and not the object itself. The object itself is stored at the address which the variable points to. Let’s suppose we have a class called SomeClass and that we instantiate it with a variable of the SomeClass type. So, suppose we have the following very simple code:

SomeClass someVar;

The someVar variable above is a variable of a class type – which is commonly referred to as an object. But, what actually happens behind the scenes is that someVar will just contain a reference – which is basically a memory address that points to the real object and all the class variables for that object actually lives. So, remember that a variable of a class type – or what is commonly referred to as an object of a class – really just stores a memory address that points to the real object. Bottom line: anytime you see a variable of a class type like the someVar variable above, just remember that it is basically a reference that stores an address in memory.

Confused yet?
An example and some diagrams will help make this very clear. Suppose we have a class called PersonClass, which has a method called set that just sets the name and age for a given Person object. The details of the class itself don’t matter for the purpose of this example so we won’t bother to show the implementation of PersonClass. Now, let’s say we have the following code:

//create an object by passing in a name and age:
PersonClass variable1 = new PersonClass("Mary", 32);

PersonClass variable2;

// Both variable2 and variable1 now both name the same object
variable2 = variable1; 

/*this also changes variable1, since variable 2 and variable1
   name the same exact object: */

variable2.set("Jack", 22);

System.out.println(variable1);

Let’s just assume that System.out.println method above will print the name and age of a PersonClass object – even though this is not correct, it does keep the example simple and easy to understand. So, if we run the code above, the output will be:

Jack 22




In the code above, you can see that when we made a change to variable2, that it also changed variable1. This might confuse you into thinking that because of that fact Java is pass by reference – and you would be very WRONG. Both variable1 and variable2 hold a reference to the same object in memory – and this happened when we ran this line of code “variable2 = variable1″. When we use the assignment operator (the “=”) with variables of a class type, then we are copying that reference value – in other words variable2 is given the memory address (or reference) that is being stored in variable1. Remember that the word reference means the same thing as memory address. This assignment of references is best displayed by actual drawings, which we show below:

An illustration of pass by value in Java

So, looking at the images above it should be clear that variable1 and variable2 are just two different references to the same exact spot in memory. Because of the fact that the statement “variable2 = variable1″ essentially just copies the reference from variable1 into variable2, this is pass by value. You should think of the reference (which is a memory address) as the value, and in this case that reference is what is being copied. And, that is exactly what pass by value means – a copy of a value is passed to another variable. You should also read our article on the differences between primitive types and reference types here: Primitive type vs Reference type.

Let’s go through one last example. Let’s say we have the following code:

//create an object by passing in a name and age:
PersonClass variable1 = new PersonClass("Mary", 32);

PersonClass variable2;

//Both variable2 and variable1 now reference the same object
variable2 = variable1; 


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

// variable1 now points to variable3
variable1 = variable3;

//WHAT IS OUTPUT BY THIS?
System.out.println(variable2);
System.out.println(variable1);

If we run the code above it will output the code below:

Mary 32
Andre 45

The key to understanding the code above is the fact that changing the object that variable1 points to does not change variable2. So, even though variable1 is changed to point to a different object, that has no effect whatsoever on variable2. Hopefully that is clear to you – that variable1 and variable2 are not interchangeable – they are different variables that just store the same value – at least until the “variable1 = variable3” statement. And that should prove to you that Java passes objects by value, and everything else for that matter.

Is it possible to pass an object by reference in Java?

No, there are no “extra” language features in Java that would allow for you to pass an object by reference in Java. Java is strictly pass by value, and does not give the programmer the option of passing anything by reference.

Are arrays passed by reference in Java?

Arrays in Java are also objects. And what did you learn about objects in Java? Well, that they are passed by value and not passed by reference. And the same is true for arrays in Java – they are passed by value and not by reference. Of course, like any other class object, when an array is passed to another method that method can still change the contents of the array itself. But, what is being passed to the method is a copy of the reference address that points to the array object. Just take a look at our example above for the PersonClass – the same exact principles apply to arrays since they are objects in Java, and are passed by value.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

  • ravi katiyar

    this is lovely.. thank you 🙂

  • Vivek Lande

    if i want to use pass by reference in java, how to do it..

  • sowmya

    Hi, I din’t get the line assigning variable1 = variable2. variable2 value will be null rite how can you tell that variable1=variable2 points to 4032 memory location. If we assign like that both references will be null in my view. I’m confused..Please clarify my doubt

  • seema

    good post…..explained it very well with examples and diagrams.

  • rohit

    good job..
    🙂

  • Levine Veblen

    good guy, wonderful explantion! keep it up

  • To The Point

    Thanks for the explanation.

  • 975671 962975oh properly, Alicia silverstone is matured nowadays but when she was nonetheless younger, she may be the sex symbol of hollywood` 42092

  • 381585 75648A thoughtful insight and ideas I will use on my website. Youve obviously spent some time on this. Congratulations! 451867

  • 600336 663974You got a very good website, Gladiola I discovered it through yahoo. 630399

  • 307132 247904Your weblog is among the far better blogs Ive came across in months. Thank you for your posts and all of the finest together with your function and weblog. Searching forward to reading new entries! 313325

  • Sujith krishnan

    thanks for explanation

  • Nirmal

    Hi, thanks for the information. it was realy helpful to be clear on some concepts.

    With regards to this I have a question. In the case of a Hashmap, is

    HashMap names = new HashMap();
    Set nameKeys = names.keySet();

    nameKeys.remove(somekey); has an affect on the actual Hashmap too.

    Is this too due to the readson that the 2 objects share the same address.

    Could you please help me to understand this?

  • Gustavo

    Ok, after reading a lot of texts related to this reference-value thing in Java, I think I can explain the confusion in short (the “why” people sometimes start a fight around this):

    Depending on the point of view you are in, Java passes parameters by reference and value, or just by value, Why? Because of a simple reason: People consider the reference passed by java like a value. They’re right, at the lowest level we can just pass a value to a method, yes, it can be an object’s reference, but in the simplest sense it still a value.

    Now, it is true that I can say “it’s by reference” appealing to the next code:

    //Main.java:
    class Main
    {
    public static void main(String[] args)
    {
    Dog dog = new Dog(“Lazy”, 8);
    changeDog(dog);
    System.out.println(dog.name);
    }
    private static void changeDog(Dog dog)
    {
    dog.name = “another name”;
    }
    }

    //Dog.java:
    class Dog
    {
    String name;
    Integer age;
    Dog(String name, Integer age)
    {
    this.name = name;
    this.age = age;
    }
    }

    After running this I get “another name” so it looks like Java is passing the object itsef to the method, but it’s just a copy of its reference. If I add this line:

    dog = new Dog(“Puppy”, 1);

    before: dog.name = “another name”;

    you can check that Java actually passes just a copy of the reference, so when I create “Puppy” I’m modifying the reference “living” in changeDog() but not the reference living in main().

    In conclusion, yes Java can pass by reference, but it’s a copy of the reference where the function was called (in the simplest sense, a value), as long as you do not modify that reference, it will work for modifying the object which is pointing at (you have 2 copies of the reference pointing to the same Object).

  • Amit

    Awesome

  • Babar Hussain

    There is a mistake in bellow image representation
    we can not assign uninitialized object to another
    so it can not be like
    PersonClass variable1 = new PersonClass(“mary”, 32);
    PersonClass variable2;
    variable1 = variable2

    please correct it

  • Guest

    There is a mistake in bellow image representation
    we can not assign uninitialized object to another
    so it can not be like
    PersonClass variable1 = new PersonClass(“mary”, 32);
    PersonClass variable2;
    variable1 = variable2

    please correc

  • Guest

    There is a mistake in bellow image representation
    we can not assign uninitialized object to another
    so it can not be like
    PersonClass variable1 = new PersonClass(“mary”, 32);
    PersonClass variable2;
    variable1 = variable2

    please correct it
    😉

  • Guest

    There is a mistake in bellow image representation
    we can not assign uninitialized object to another
    so it can not be like
    PersonClass variable1 = new PersonClass(“mary”, 32);
    PersonClass variable2;
    variable1 = variable2

    please correct it
    😉

  • Guest

    There is a mistake in bellow image representation
    we can not assign uninitialized object to another
    so it can not be like
    PersonClass variable1 = new PersonClass(“mary”, 32);
    PersonClass variable2;
    variable1 = variable2

    please correct it
    😉

  • Pramod

    Good explanation. Easy understandable 🙂

  • Gopinath M B

    Good one buddy 🙂

  • Faisal

    Really very clear explanation. Thank u so much

  • Utsav Singhal

    A quick explanation on my blog

    http://choosejava.blogspot.in/2014/05/primitives-and-references-are-passed-by.html

    Hope this helps as well!

  • In this case the Receiving method should be static, otherwise the compiler will throw a “non-static method Receiving(int) cannot be referenced from a static context” error.

  • Fer Raviola

    This is GREAT!. Your explanation was perfect. Enjoyable to read, very clear and to the point. Thank you very much!. keep doing this.

  • yyz

    your explanation is awesome, simple and clean to understand. Never shut down this website, if you want, we can donate money for your website.

  • pranav

    package pranav;

    import java.util.Scanner;

    public class SortedArray

    {

    public int[] sort11(int[] a)

    {

    int t;

    for (int j = 0; j < 5; j++)

    {

    for (int i = 0; i <4; i++)

    {

    if (a[i + 1] < a[i])

    {

    t=a[i];

    a[i]=a[i+1];

    a[i+1]=t;

    }

    }

    }

    return a;

    }

    public static void main(String args[])

    {

    int b[]= new int[5];

    int z[]= new int[5];

    for (int i = 0; i < 5; i++)

    {

    Scanner sc = new Scanner(System.in);

    b[i] = sc.nextInt();

    }

    SortedArray h = new SortedArray();

    h.sort11(b);

    for (int k = 0; k < 5; k++)

    {

    System.out.println(b[k]);

    }

    }

    } so cl by refrence.

  • vivek

    awesome!!

  • binay

    great explanation. Thanks.

  • GuestHero

    Ok, honestly, BEST EXPLANATION EVER. AMAZING JOB! 🙂

  • Aris

    excellent explanation!!

  • Prem

    Great explanation!

  • Sumit

    How about below example.. some how your explanation of “strictly pass by value” not working for me. if you can explain me this example. also i went through below C++ explanation from where we all got the idea.

    http://courses.washington.edu/css342/zander/css332/passby.html

    class PassByValueRefrecne {
    private String name;
    private String age;

    }

    public class PassByValueRefrecneTest {

    public static void main(final String[] args) {

    PassByValueRefrecne byValueRefrecne = new PassByValueRefrecne(“Name”, “age”);

    String byValueRefrecneStr = “StringValue”;

    int number = 10;

    System.out.println(” Before Method Call”);

    System.out.println(” byValueRefrecne :: ” + byValueRefrecne.toString());

    System.out.println(” byValueRefrecneStr :: ” + byValueRefrecneStr);

    System.out.println(“number :: ” + number);

    final PassByValueRefrecneTest byValueRefrecneTest = new PassByValueRefrecneTest();

    byValueRefrecneTest.updateValues(byValueRefrecne);

    byValueRefrecneTest.updateValues(byValueRefrecneStr);

    byValueRefrecneTest.updateValues(number);

    System.out.println(” ++++++++++++++++++++++++++++++++++++”);

    System.out.println(” After Method Call”);

    System.out.println(” byValueRefrecne :: ” + byValueRefrecne.toString());

    System.out.println(” byValueRefrecneStr :: ” + byValueRefrecneStr);

    System.out.println(“number :: ” + number);

    System.out.println(” ++++++++++++++++++++++++++++++++++++”);

    PassByValueRefrecne byValueRefrecne1 = byValueRefrecne;

    byValueRefrecne1.setName(“Sumit Gupta”);

    System.out.println(” byValueRefrecne1 :: ” + byValueRefrecne.toString());

    System.out.println(” byValueRefrecne :: ” + byValueRefrecne1.toString());

    }

    public void updateValues(PassByValueRefrecne byValueRefrecne) {

    byValueRefrecne.setAge(“NewAge”);

    byValueRefrecne = new PassByValueRefrecne(“NewName”, “SomeOtherNewAge”);

    byValueRefrecne.setAge(“SomeOtherNewAge111”);

    // byValueRefrecne = byValueRefrecne2;

    }

    public void updateValues(String byValueRefrecne) {

    byValueRefrecne = new String(“byValueRefrecne”);

    }

    public void updateValues(int byValueRefrecne) {

    byValueRefrecne = 20;

    }

    }

  • This is indeed great explanation! Thank you!!

  • Tapan

    excellent explanation…thanks