Tutorial

Java is Pass by Value, Not Pass by Reference

Updated on December 6, 2022
authorauthor

Pankaj and Andrea Anderson

Java is Pass by Value, Not Pass by Reference

Introduction

Many Java programmers question whether Java is pass by value or pass by reference. This article summarizes why Java is always pass by value.

First, what does pass by value and pass by reference mean?

  • Pass by value: The method parameter values are copied to another variable and then the copied object is passed to the method. The method uses the copy.
  • Pass by reference: An alias or reference to the actual parameter is passed to the method. The method accesses the actual parameter.

Often, the confusion around these terms is a result of the concept of the object reference in Java. Technically, Java is always pass by value, because even though a variable might hold a reference to an object, that object reference is a value that represents the object’s location in memory. Object references are therefore passed by value.

Both reference data types and primitive data types are passed by value. Learn more about data types in Java.

In addition to understanding data types, it’s also important to understand memory allocation in Java, because reference data types and primitive data types are stored differently.

Demonstrating pass by value

The following example demonstrates how values are passed in Java.

The example program uses the following class:

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;
	}
}

The following example program uses a generic method, swap(), that swaps two variables. Another method, changeValue(), attempts to change the variable values.

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("After the swap method executes:");
		System.out.println("`red` color value = " + red.getColor());
		System.out.println("`blue` color value = " + blue.getColor());
		
		changeValue(blue);
		System.out.println("After the changeValue method executes:");
		System.out.println("`blue` color value = " + blue.getColor());
		
	}

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

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

}

When you execute the example program, you get the following output:

Output
After the swap method executes: 'red' color value = Red 'blue' color value = Blue After the changeValue method executes: 'blue' color value = Red

The output shows that the swap() method didn’t swap the color values of the original objects. This helps to show that Java is pass by value, since the swap() method only acts upon copies of the original object reference values.

This swap() method test can be used with any programming language to check whether it’s pass by value or pass by reference.

The Example swap() Method Explained

When you use the new operator to create an instance of a class, the object is created and the variable contains the location in memory where the object is saved.

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

Here’s a step-by-step breakdown of what happens when the swap() method executes:

  • Assume that red is pointing to memory location 50 and blue is pointing to memory location 100, and that these are the memory locations of both Balloon objects.

  • When the class calls the swap() method with the red and blue variables as arguments, two new object variables, o1 and o2, are created. o1 and o2 also point to memory locations 50 and 100 respectively.

  • The following code snippet explains what happens within the swap() method:

    public static void swap(Object o1, Object o2) { // o1 = 50, o2 = 100
    	Object temp = o1; // assign the object reference value of o1 to temp: temp = 50, o1 = 50, o2 = 100
    	o1 = o2; // assign the object reference value of o2 to o1: temp = 50, o1 = 100, o2 = 100
    	o2 = temp; // assign the object reference value of temp to o2: temp = 50, o1 = 100, o2 = 50
    } // method terminated
    
  • The values of o1 and o2 are swapped, but because the values are copies of the red and blue memory locations, there is no change to the values of the red and blue color values.

Since the variables contain the reference to the objects, it’s a common mistake to assume that you’re passing the reference and Java is pass by reference. However, you’re passing a value which is a copy of the reference and therefore it’s pass by value.

The Example changeValue() Method Explained

The next method in the example program changes the color value of the object referenced by the blue variable:

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

Here’s a step-by-step breakdown of what happens within the changeValue() method:

  • The class calls the changeValue() method on the blue variable that references memory location 100. The first line creates a reference that also points to memory location 100. The color value of the object at memory location 100 is changed to "Red".

  • The second line creates a new object (with color value "Green"). The new object is at memory location 200. Any further methods executed on the balloon variable act upon the object at memory location 200, and don’t affect the object at memory location 100. The new balloon variable overwrites the reference created in line 1 and the balloon reference from line 1 is no longer accessible within this method.

  • The third line changes the color value of the new Balloon object at memory location 200 to "Blue", but does not affect the original object referenced by blue at memory location 100. This explains why the final line of the example program output prints blue color value = Red, which reflects the change from line 1.

Conclusion

In this article you learned about why Java is pass by value. Continue your learning with more Java tutorials.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 5, 2014

hai This is vijay here u are having a very good interview questions which are very helpfull during interview. i have been asked one qus in gtt is that : purpose of class inside interface with example. i saw lot of blogs but doesnt get clearity…so plz post the answer for this qus also. Thx in advance.

- vijay sakhare

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 6, 2014

    So, if it is not by reference, so can you please explain the program as below : public class Test { public static void main(String[] args) { Employee emp1 = new Employee(“Employee 1”); System.out.println("Call for Emp1 " + emp1); nameChange(emp1); System.out.println(“Name change DONE”); System.out.println("Call for Emp1 " + emp1); } public static void nameChange(Employee e1){ e1.setName(“Employee 3”); } } class Employee { String name; Employee(String nam){ this.name = nam; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Object for "+ this.name; } } Becouse it is producing the output as Call for Emp1 Object for Employee 1 Name change DONE Call for Emp1 Object for Employee 3

    - Atul

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 6, 2014

    Again I would suggest read the full post, especially foo() method explanation for this.

    - Pankaj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 6, 2014

      Hi, public class Test { public static void main(String[] args) { Balloon blue = new Balloon(“Blue”); foo(blue); System.out.println(blue.getColor()); } private static void foo(Balloon balloon) { balloon.setColor(“Red”); } } The output of the above program is Red. So, the above isn’t pass by reference ?

      - Praveen

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 6, 2014

      Think of it like two strings attached to a single balloon, the original one “blue” and at the time of invoking foo(), another one named “balloon”. Now if you will pull any of these, the balloon will be pulled towards you but as soon as you attached the “balloon” string to another balloon object, any further changes will not be done to the original object. This is “Pass by Value” and we are passing COPY of the reference.

      - Pankaj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 6, 2014

      I am still confused. It seems java supports both pass by value and reference. In swap case it is pass by value. foo method in my previous comment acts as reference.

      - Praveen

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        August 13, 2014

        You got it all wrong man. You used strings in the above example, try using StringBuilder or StringBuffer, and see what you get.

        - Anonymous

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          December 2, 2014

          Hope below code might explain why its pass by value :-) public static void main(final String[] args) { String test = “Check me”; foo1(test); System.out.println(test); foo2(test); System.out.println(test); } public static void foo1(String str) { str = null; } public static void foo2(String str) { str = str + “abhi”; } Output:- Check me Check me

          - Abhi

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          March 30, 2020

          Apologies for late reply (6 years!) but String is a primitive hence you get those results. Java is pass-by-value for primitives and pass-by-reference for non-primitives.

          - James

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 6, 2014

            Correctly to say that each object variable is reference and we can only pass this reference to method or reassign variable with new reference. I think you compare with C/C++. Where on language level is supported passing reference to reference (pointer to pointer). And data of object is not related to variable. We can pass address of variable which contain address where object is located. I think you understand me. In Java such functionality is not supported on language level. and to do this it require to create a new instance of your class with field which will hold a variable with reference to your object. For example, you want to pass Integer to method and change it in the body of that method but there is no method to change value of Integer object. So you need to create wrapper class for that Integer object and pass it to method.

            - Victor

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              August 6, 2014

              So, java pass object by reference

              - Victor

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                August 6, 2014

                Before reading this post, i have understood this core concept, but realised it after i read this post. Java is always pass by value, value will be always primitive. Value can never be Object type, infact if we are passing object it seems we are passing the memory address of that object. This memory address is again an int value. Most of the books, authors failed to explain this. So here it is GREAT. “Java is pass by value, and sometimes pass through reference”.

                - Manu M

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  August 6, 2014

                  Hi Pankaj, thanks for including this nice post with good explanation. This post is very simple and easy to understand the reason for ‘why Java is pass by value but not by reference’. From your post it is clear that reference means reference to the memory location of the object. Each memory location holds a number i.e VALUE. This value is useful in identifying that memory location. So If there is a reference to an object, it means it is reference to the address location of that object. So, java refers the objects by their memory address. The name used to refer that memory location (i.e value) is termed as reference variable. As we are passing the reference of the memory location, java is pass by value (of the memory address of the object) but not pass by reference. One suggestion, if you would have added the explanation about primitive data types also, it would have helped many readers in understanding why swap method works in case of primitives but not objects. However, this is a very nice post right to the point.

                  - johny

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    August 9, 2014

                    Thanks i was confused from last month…

                    - Singh

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      August 13, 2014

                      Nice Explanation sir.Thanks

                      - Venkata Sriram

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        August 21, 2014

                        These definitions are very counter intuitive. When your argument to a function is an object, java creates a copy of the “object reference” and passes that into the function scope. So, you are feeding in a reference to an object, which is a memory address, and because it is a copy of the original, Java becomes “pass by value.” Intuitively you would assume that passing in a reference somehow cannot be considered “pass by value” since it is called a reference. Definitions like this are part of the reason so many people are intimidated by coding. In my computer science courses, professors have started saying that objects as arguments in java are “pass by reference” because you are passing in their reference. Only way to change the status quo I suppose.

                        - Dan

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        August 22, 2014

                        I loved your comment, this is the reason for all the confusion around it.

                        - Pankaj

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          August 22, 2014

                          But in case of pass by value ,since a copy is passed the original one doesnt get changed which occurs in case of primitive data types ,but same we do in case of Objects ,its original value gets changed

                          - Pankaj Tandakar

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            December 8, 2014

                            I think that the post topic is somehow misleading/confusing. Of course Java is pass by value for primitives and pass by reference for objects - you even proved that drawing arrows (references!, not values). On the other hand those references (i.e. memory location addresses) are passed by value - that is how I think it should be understood.

                            - konrad

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              January 22, 2015

                              Great explanation, thank you.

                              - Igorovics

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                April 17, 2015

                                Hi Pankaj, from the video i understood exactly, so the video solution is much much better, thanks for all your work, your site is always a “reference” for my java development understanding. thanks and keep doing your thing. Stefan from Romania.

                                - Stefan Banu

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  May 22, 2015

                                  Very nicely explained

                                  - Rahul Jain

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    June 17, 2015

                                    It was a great post. In video you are using stack memory for static methods memory allocation.Can you please explain why so?.Static methods exist in pergen space of heap

                                    - Brihati Jain

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      September 6, 2015

                                      good one. Aprreciated

                                      - bin

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        January 20, 2016

                                        Very useful explanation and tutorial in whole. Thanks.

                                        - Olga Guskova

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          February 4, 2016

                                          Really good explanation (especially on the video content)

                                          - Esakki

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            March 9, 2016

                                            good post ,Thanks

                                            - qiangyu

                                              Try DigitalOcean for free

                                              Click below to sign up and get $200 of credit to try our products over 60 days!

                                              Sign up

                                              Join the Tech Talk
                                              Success! Thank you! Please check your email for further details.

                                              Please complete your information!

                                              Become a contributor for community

                                              Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                              DigitalOcean Documentation

                                              Full documentation for every DigitalOcean product.

                                              Resources for startups and SMBs

                                              The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                              Get our newsletter

                                              Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                              New accounts only. By submitting your email you agree to our Privacy Policy

                                              The developer cloud

                                              Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                              Get started for free

                                              Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                              *This promotional offer applies to new accounts only.