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
        August 13, 2014

        I don’t know what you meant, can you comment with sample code?

        - Pankaj

          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
          January 31, 2021

          What? String isn’t primitive, String is a class and here we are making an object of that string class

          - Aqsa

            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
                            March 30, 2016

                            Totally agree with your opinion. I believe “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.” is misunderstanding. Because right description should be “Pass by Value: The method parameter values are copied to another variable and then the copied reference is passed, that’s why it’s called pass by copied reference.” Bejond

                            - Bejond

                              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

                                              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
                                                March 30, 2016

                                                Totally agree with your opinion. I believe “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.” is misunderstanding. Because right description should be “Pass by Value: The method parameter values are copied to another variable and then the copied reference is passed, that’s why it’s called pass by copied reference.” Bejond

                                                - Bejond

                                                  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

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  June 9, 2016

                                                                  Thank you so much for creating video. Your tutorials are really helpful.

                                                                  - Narendra Koli

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  June 9, 2016

                                                                  You are welcome Narendra.

                                                                  - Pankaj

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    June 23, 2016

                                                                    Dear Mr. Pankaj, I have a confusion with this method: private static void foo(Balloon balloon) { //baloon=100 // line1 balloon.setColor(“Red”); //baloon=100 balloon = new Balloon(“Green”); //baloon=200 balloon.setColor(“Blue”); //baloon = 200 } In Line1,Could you please tell me why balloon points to “Blue” Object instead of “Red” Object ?

                                                                    - Albert

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    June 27, 2016

                                                                    At line 1, object refers to Blue color Balloon object. From caller we passed Blue color Balloon object.

                                                                    - Lakshman

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      July 13, 2016

                                                                      Hi, Can you please declare an array of integer and initialize it with some values. then pass this array to some method (return type void) and add 1 to all of the elements in array. and come back in main and try to print array element… this will print the incremented values. Can you do clear this thing why its happens.

                                                                      - Mandeep Sharma

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        July 19, 2016

                                                                        I understand that Java is always pass by value, what I don’t understand is what exactly is the difference between pass an object by reference and pass an object reference by value. If you pass the reference value, isn’t that essentially the same thing? What would change in the swap and balloon examples? Currently I only understand the fact that calling the class’s constructor allocates a different memory set for the variable, otherwise I can’t see the difference. That’s why a lot of people say that Java passes objects by reference, because the behavior, if not identical, is extremely similar.

                                                                        - Gadrov

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          July 19, 2016

                                                                          Damn it., That’s one of the simplest way to explain it. Thanks a ton Guru :)

                                                                          - Praveen

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            September 13, 2016

                                                                            Man, you’re so confused it’s not funny. Stop writing stuff on the internet, people here believe all they see. Consider this - it’s an equivalent C program that passes a struct by reference and the behaviour is exactly the same as in Java: #include typedef struct s { const char *colour; } balloon; void swap (balloon *b1, balloon *b2) { balloon *tmp = b1; b1 = b2; b2 = tmp; } int main (int argc, char **argv) { balloon b1, b2; b1.colour = “red”; b2.colour = “blue”; swap (&b1, &b2); printf (“red: %s, blue: %s\n”, b1.colour, b2.colour); return 0; }

                                                                            - Renat

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            September 13, 2016

                                                                            First of all here we are talking about Java. Even after reading and hopefully understanding above program, you don’t understood then I feel for you. Read again, may be somewhere else… nothing else I can do for you.

                                                                            - Pankaj

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              September 14, 2016

                                                                              Your code does not pass by reference, it passes pointer by value. Moreover, there is no such thing as “reference” in C, it exists only in C++: #include typedef struct s { const char *colour; } balloon; void swap (balloon &b1_r, balloon &b2_r) { balloon tmp = b1_r; b1_r = b2_r; b2_r = tmp; } int main (int argc, char **argv) { balloon b1, b2; b1.colour = “red”; b2.colour = “blue”; swap (b1, b2); printf (“red: %s, blue: %s\n”, b1.colour, b2.colour); return 0; }

                                                                              - Vlad

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                September 21, 2016

                                                                                Hello. Thanks for a good explanation. Yet, I suppose, there is an issue what to mean passing by value or by reference. Look there –https://www.careerride.com/C++-pass-by-value-and-pass-by-reference.aspx. I like very much the idea, that the main difference is: By val – The procedure code does not have any access to the underlying element in the calling code; By ref – The procedure code gives a direct reference to the programming element in the calling code. So, to my mind it is not clear that swap method is a correct way to obviously say if a language passes vars by value or by ref.

                                                                                - Vyacheslav

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                September 21, 2016

                                                                                Well, also a good article: https://javadude.com/articles/passbyvalue.htm. Java doesn’t support variable references, so, we can not speak at all about passing by reference in Java.

                                                                                - Vyacheslav

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  December 30, 2016

                                                                                  Thanks Pankaj for explaining it more clearly in video. Now doubt is cleared.

                                                                                  - Jagadish

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    January 9, 2017

                                                                                    Thanks a lot pankaj. That was a very good explanation.

                                                                                    - Arunkumar

                                                                                      JournalDev
                                                                                      DigitalOcean Employee
                                                                                      DigitalOcean Employee badge
                                                                                      January 15, 2017

                                                                                      Very Urgent please help me. Can you explain me how to draw memory diagram for following java code. public class ArrayOfReferences { public static void main(String[] args) { String[] names; /* How many objects do we have? */ int numberOfNames = 3; Scanner scanner = new Scanner(System.in); /* Reading names */ names = new String[numberOfNames]; /* How many objects do we have? */ for (int idx = 0; idx < names.length; idx++) { System.out.println("Enter the name of a friend: "); names[idx] = scanner.next(); } /* Printing names */ System.out.println("Your friends are: "); for (int idx = 0; idx < names.length; idx++) { System.out.println(names[idx]); } scanner.close(); } }

                                                                                      - Bhagwati Lal

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        February 8, 2017

                                                                                        Hi Pankaj, Thanks for such a wonderful article. I have one question based on your article. import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { List a = new ArrayList(); a.add(“Apple”); System.out.println(“LIST SIZE”+a.size()); addInList(a, “Banana”); addInList(a, “COFFEE”); System.out.println(“LIST SIZE”+a.size()); } public static void addInList(List list, Object ojb){ list.add(ojb); System.out.println(“LIST SIZE::”+list.size()); } } output: LIST SIZE1 LIST SIZE::2 LIST SIZE::3 LIST SIZE3 If java support pass by value then why list size is modified In last print statement list size should be 1, Could you clarify to me Thanks Dharmendra

                                                                                        - Dharmendra

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        June 30, 2017

                                                                                        List is an object. When you pass a object to a method, you are passing the value of the memory address of the object to the method. Thus you can modify the attributes of the object. However, you cannot reassign another object to this memory address.

                                                                                        - Victor

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        August 20, 2017

                                                                                        Hi Victor, In Java, the new keyword returns a reference to a newly-constructed object. Therefore, in String s = new String(“foo”); the value of variable s is a reference to a String object In the same way List a = new ArrayList(); a should be reference to ArrayList Object Isn’t it?

                                                                                        - Disha

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          May 18, 2017

                                                                                          Excellent explanation.

                                                                                          - Rahul

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            July 26, 2017

                                                                                            this post clear my all problem. thank you keep posting

                                                                                            - Anurag Singh

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              August 2, 2017

                                                                                              Pankaj: I’m not a new programmer, but fairly new to Java. Once again your calm and helpful manner has come through for me. Thanks for the clarity.

                                                                                              - Christopher

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              August 2, 2017

                                                                                              Thanks for the kind words, appreciate it.

                                                                                              - Pankaj

                                                                                                JournalDev
                                                                                                DigitalOcean Employee
                                                                                                DigitalOcean Employee badge
                                                                                                August 29, 2017

                                                                                                it is the best explenation about pass by reference and pass by value. everything is too clear right now

                                                                                                - Pooya

                                                                                                  JournalDev
                                                                                                  DigitalOcean Employee
                                                                                                  DigitalOcean Employee badge
                                                                                                  September 4, 2017

                                                                                                  Awesome explanation, thanks

                                                                                                  - Balwinder Singh

                                                                                                    JournalDev
                                                                                                    DigitalOcean Employee
                                                                                                    DigitalOcean Employee badge
                                                                                                    November 21, 2017

                                                                                                    I believe that you don’t fully understand pass by value and pass by reference. primitive parameters are passed by value. reference parameters are passed by reference. pass by value means a copy of the primitive is sent to the method - any changes to the parameter will not change the original value. pass by reference means that the address of the object is sent to the method - any changes to the parameter’s instance members will result in that change being made in the original value… What you are talking about in this article has nothing to do with pass by reference, instead you are talking about changing the address that the parameter points to, to some new location in memory – the address is constant but the data that the pointer refers to is not.

                                                                                                    - William L. DeRieux IV

                                                                                                    JournalDev
                                                                                                    DigitalOcean Employee
                                                                                                    DigitalOcean Employee badge
                                                                                                    December 1, 2017

                                                                                                    +1! :-) well done! my exactly the same thoughts regarding this article!

                                                                                                    - miticosul

                                                                                                    JournalDev
                                                                                                    DigitalOcean Employee
                                                                                                    DigitalOcean Employee badge
                                                                                                    December 1, 2017

                                                                                                    Sorry to say this but your understanding about “Pass by Reference” and “Pass by Value” is not correct. Below quote properly describes it: Passing by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself). Pass by value means the called functions' parameter will be a copy of the callers' passed argument. The value will be the same, but the identity - the variable - is different. Also refer this StackOverflow Post: https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value

                                                                                                    - Pankaj

                                                                                                      JournalDev
                                                                                                      DigitalOcean Employee
                                                                                                      DigitalOcean Employee badge
                                                                                                      August 27, 2018

                                                                                                      I think, there is a serious misunderstanding in the article, regarding pass by reference. The swap method is just swapping the argument references and not the actual values, hence it doesn’t have effect. And as far as the definition is concerned, whatever pankaj wrote is correct, however his understanding is not. In pass by reference, instead of passing a copy of the parameters, we pass the reference or the identifier which holds the address of the parameters. And swapping references doesn’t mean swapping values which is the case here. Here is a sample program from C, void swap(int* a, int* b){ //Swapping the argument references int* c = NULL; c = a; a = b; b = c; } void swap2(int** a, int** b){ //Swapping the actual references int* c = NULL; c = *a; *a = *b; *b = c; } int main(){ int *a = NULL; int *b = NULL; a = (int*) malloc ( sizeof(int)); b = (int*) malloc ( sizeof(int)); *a = 1; *b = 2; printf(“\n%d,%d”, *a , *b); swap(a,b); printf(“\n%d,%d”, *a , *b); swap2(&a,&b); printf(“\n%d,%d”, *a , *b); return 0; }

                                                                                                      - Mohan

                                                                                                        JournalDev
                                                                                                        DigitalOcean Employee
                                                                                                        DigitalOcean Employee badge
                                                                                                        May 4, 2018

                                                                                                        +1 to William’s answer. Your test is not about pass by value / reference. Please replace it will valid test to avoid further confusion. Java is pass by value for primitives and pass by reference for objects. Please correct your misleading tutorial.

                                                                                                        - Govind Ostwal

                                                                                                        JournalDev
                                                                                                        DigitalOcean Employee
                                                                                                        DigitalOcean Employee badge
                                                                                                        July 30, 2018

                                                                                                        agree! //pass by value for primitives public static void main(String[] args) { Integer a = 13; Integer b = 179; System.out.println(“a1:” + a + " b1:" + b);//a1:13 b1:179 swap(a, b); System.out.println(“a2:” + a + " b2:" + b);//a2:13 b2:179 modify(b); System.out.println(“b3:” + b);//b3:179 } public static void swap(Integer c, Integer d) { System.out.println(“c1:” + c + " d1:" + d);//c1:13 d1:179 Integer temp = c; c = d; d = temp; System.out.println(“c2:” + c + " d2:" + d + " temp:" + temp);//c2:179 d2:13 temp:13 } public static void modify(Integer e) { System.out.println(“e1:” + e);//e1:179 e = 241; System.out.println(“e2:” + e);//e2:241 } //pass by reference for objects public static void main(String[] args) { Balloon a = new Balloon(“Red”); Balloon b = new Balloon(“Blue”); System.out.println(“a1:” + a + " " + a.getColor());// Balloon@7852e922 Red System.out.println(“b1:” + b + " " + b.getColor());// Balloon@4e25154f Blue swap(a, b); System.out.println(“a2:” + a + " " + a.getColor());// Balloon@7852e922 Red System.out.println(“b2:” + b + " " + b.getColor());// Balloon@4e25154f Blue modify(b); System.out.println(“b3:” + b + " " + b.getColor());// Balloon@4e25154f Red } public static void swap(Balloon c, Balloon d) { System.out.println(“c1:” + c + " " + c.getColor());// Balloon@7852e922 Red System.out.println(“d1:” + d + " " + d.getColor());// Balloon@4e25154f Blue Balloon temp = c; c = d; d = temp; System.out.println(“c2:” + c + " " + c.getColor());// Balloon@4e25154f Blue System.out.println(“d2:” + d + " " + d.getColor());// Balloon@7852e922 Red System.out.println(“temp:” + temp + " " + temp.getColor());// Balloon@7852e922 Red } public static void modify(Balloon e) { System.out.println(“e1:” + e + " " + e.getColor());// Balloon@4e25154f Blue e.setColor(“Red”); System.out.println(“e2:” + e + " " + e.getColor());// Balloon@4e25154f Red e = new Balloon(“Green”); System.out.println(“e3:” + e + " " + e.getColor());// Balloon@70dea4e Green e.setColor(“Blue”); System.out.println(“e4:” + e + " " + e.getColor());// Balloon@70dea4e Blue }

                                                                                                        - Alice

                                                                                                          JournalDev
                                                                                                          DigitalOcean Employee
                                                                                                          DigitalOcean Employee badge
                                                                                                          November 21, 2018

                                                                                                          Agree that this is a misleading article, especially for new developers. What he says is correct, but its not the most relevant thing to understand. The important thing to understand is that Java uses pass by value for primitives and pass by reference for objects. The unfortunate thing is this article pops up as the first result in google and may people are thinking this is the right way. I would request to correct/rewrite it

                                                                                                          - Binith

                                                                                                            JournalDev
                                                                                                            DigitalOcean Employee
                                                                                                            DigitalOcean Employee badge
                                                                                                            March 14, 2018

                                                                                                            Appreciate your vedio

                                                                                                            - Himanshu

                                                                                                              JournalDev
                                                                                                              DigitalOcean Employee
                                                                                                              DigitalOcean Employee badge
                                                                                                              March 16, 2018

                                                                                                              Do you really ask this question in job interviews? These are the type of questions that make common interview practices as useful as a coin flip. Java passes variables by value (where object non primitive variables are actually references to an object). If someone can demonstrate they know how this works, rather than trying to answer a question that is known to be interpreted different ways. Have you ever known someone where answering this was the proving factor on their success? I guarantee there are people that have read that java passes object references by value, but would not be able to tell you the output of your tests. Please stop asking questions like this. Everyone, please stop using interview questions like this. Asking “is java pass by value or pass by reference” when you know people are going to get confused looks on their faces only serves the purpose of feeding ones ego an sense of supiority. Instead try seeing if the candidate can actually write correct functioning code, that they can grok what code examples may do. More importantly, put an effort in the interview to determine if the candidate is bright, driven and a strong personality fit for your team. This will improve your rate of hiring strong team members. Itwill reduce the number of false negatives which come from candidates incorrectly answering pointed trivia questions that help the interviewer feel good about themselves. It will also reduce the number of missed job opportunities for candidates who were asked poor questions that prove nothing about potential for success. The interview is. It about you (the I terviewer) it is about the candidate. Don’t leave an interview feeling smart because you were able to trick a candidate. Instead, leave the interview feeling good because you helped the candidate really show what the have to offer. Sorry to rant - I get frustrated with people perpetuating poor interview practices for the ‘80s. I know there are other good articles here that help provide deeper understanding of java. However, this article just feels disingenuous and a little smug to me.

                                                                                                              - David

                                                                                                              JournalDev
                                                                                                              DigitalOcean Employee
                                                                                                              DigitalOcean Employee badge
                                                                                                              March 16, 2018

                                                                                                              Hi David, If you have faced or taken a lot of interviews, you must know that it’s not only about giving correct answers. Nobody expects to get 100% correct answers and any good interviewer don’t judge if an answer is wrong. Some questions are confusing and they are still asked to see how interviewee responds to it, how he reacts when follow-up or counter questions are asked. Technical knowledge can get you only half way, confidence, way of talking, problem solving approach, soft skills play a vital role in getting a job. The article is written to help you understand the topic clearly, there is nothing “disingenuous and a little smug” part in it.

                                                                                                              - Pankaj

                                                                                                                JournalDev
                                                                                                                DigitalOcean Employee
                                                                                                                DigitalOcean Employee badge
                                                                                                                April 26, 2018

                                                                                                                Hello Pankaj, If you think the program is passing balloon objects as pass by value. Consider this program, it is swapping the values now. package com.baloon; 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()); } //Generic swap method public static void swap(Balloon o1, Balloon o2){ /* Object temp = o1; o1=o2; o2=temp; */ o1.setColor(“Blue”); o2.setColor(“Red”); } } Output : red color=Blue blue color=Red

                                                                                                                - Lokesh

                                                                                                                  JournalDev
                                                                                                                  DigitalOcean Employee
                                                                                                                  DigitalOcean Employee badge
                                                                                                                  May 3, 2018

                                                                                                                  You all fighting terminology here. Look at Assembly, where everything is a value, period. Any other fancy name (like “reference” or “pointer”) is the way you use this value. Semantically, the sentence: “A copy of a reference is value” is false, If you changed “reference” to “dog”, and “value” to “cat” it is probably easier to see. A copy of a pointer is, well… could be a pointer. Or my mother’s birthday, if it happens to be exactly 1941. So Java is pass by value, because someone long ago stated, that a copy of a reference is a value. That’s all. Anyway, check Stackoverflow for Is Java “pass-by-reference” or “pass-by-value”?, the question is there since 2012.

                                                                                                                  - karatedog

                                                                                                                    JournalDev
                                                                                                                    DigitalOcean Employee
                                                                                                                    DigitalOcean Employee badge
                                                                                                                    May 6, 2018

                                                                                                                    I would say it is both pass-by-reference and pass-by-value and somewhat confusing. I did a litter experiment and I posted in my blog. https://programmingstacks.com/blog/java-is-both-pass-by-reference-and-pass-by-value-however/

                                                                                                                    - Progstacks

                                                                                                                      JournalDev
                                                                                                                      DigitalOcean Employee
                                                                                                                      DigitalOcean Employee badge
                                                                                                                      May 18, 2018

                                                                                                                      Hello. I’m Java Developer in Korea :) Can I upload the post to my blog translating this? The another code 'll be added of the post! If you’ll allow, please answer me. Thank you.

                                                                                                                      - ramason

                                                                                                                      JournalDev
                                                                                                                      DigitalOcean Employee
                                                                                                                      DigitalOcean Employee badge
                                                                                                                      May 18, 2018

                                                                                                                      Rather than commenting here, it would be good if you contact me directly. Usually we don’t allow republishing of our articles elsewhere.

                                                                                                                      - Pankaj

                                                                                                                        JournalDev
                                                                                                                        DigitalOcean Employee
                                                                                                                        DigitalOcean Employee badge
                                                                                                                        June 27, 2018

                                                                                                                        Thanks for the video tutorial. It really cleared the concept. Thanks a lot!!

                                                                                                                        - Parth

                                                                                                                          JournalDev
                                                                                                                          DigitalOcean Employee
                                                                                                                          DigitalOcean Employee badge
                                                                                                                          August 3, 2018

                                                                                                                          If somebody wrote something like this in a job interview, I’d politely tell her/him the interview is finished. ``` //Generic swap method public static void swap(Object o1, Object o2){ Object temp = o1; o1=o2; o2=temp; } ```

                                                                                                                          - lala

                                                                                                                          JournalDev
                                                                                                                          DigitalOcean Employee
                                                                                                                          DigitalOcean Employee badge
                                                                                                                          August 12, 2018

                                                                                                                          why dude? whats wrong? How long you have been coding in Java?

                                                                                                                          - Thiru

                                                                                                                            JournalDev
                                                                                                                            DigitalOcean Employee
                                                                                                                            DigitalOcean Employee badge
                                                                                                                            September 2, 2018

                                                                                                                            The reason people are confused is because in this blog and many other definition of pass-by-value and pass-by-reference has been changed. probably because its coming from a who never considered C++ probably mother of all modern languages while having this discussion. Actually your foo example is exactly tells us Java is pass-by-reference since as per C++ perspective. if swap method would have worked it would mean java is pass-by-reference-of-reference. In c++ this is referred as double pointer (**). Now let me write definitions. pass-by-value: If you pass in an object and callee changes any value it would not be available because when caller called the method application cloned a new object in the stack memory and pass in the calee. pass-by-reference: If you pass in an object and callee changes any value it would be available because when caller called the method application provided the value of reference of the same object so callee can change anything but one exception it can’t call on “new” on the same reference since the reference passed by value. To overcome this issue C++ provides double pointer (**) operator in this case you pass the reference of a reference to an object. in such case you can modify it as well as you can use new operator all together. In java there is no direct way available but workarounds are to use the wrapper classes.

                                                                                                                            - Mubashar

                                                                                                                            JournalDev
                                                                                                                            DigitalOcean Employee
                                                                                                                            DigitalOcean Employee badge
                                                                                                                            December 7, 2018

                                                                                                                            I’m sorry but you got it wrong. I recommend watching this video (https://www.youtube.com/watch?v=LW8Rfh6TzGg&index=5&list=PL2\_aWCzGMAwLZp6LMUKI3cc7pgGsasm2\_) to understand the situation. Also, this thread on StackOverflow may be useful: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

                                                                                                                            - 7thArcanist

                                                                                                                              JournalDev
                                                                                                                              DigitalOcean Employee
                                                                                                                              DigitalOcean Employee badge
                                                                                                                              September 24, 2018

                                                                                                                              Hi Pankaj, Thank you for your article and video. The video helped. I was still a bit confused though and tried your swap code and added my own swap2 method to call the set method explicitly on the objects o1 and o2. The effect of this does in fact change the values in the main method. So although you say it is “pass by value” what we are seeing is a change in value taking place on the called objects because we still have a reference to the objects passed to the method. public class PassbyValueExample { public static void main(String args []){ Balloon red = new Balloon(“red”); Balloon blue = new Balloon(“blue”); swap(red, blue); System.out.println("ex1. red colour = " + red.getColour()); System.out.println("ex1. blue colour = " + blue.getColour()); swap2(red, blue); System.out.println("ex2. red colour = " + red.getColour()); System.out.println("ex2. blue colour = " + blue.getColour()); } private static void swap(Object o1, Object o2){ Object temp = o1; o1 = o2; o2 = temp; } private static void swap2(Object o1, Object o2){ Object temp = o1; o1 = o2; o2 = temp; ((Balloon)o1).setColour(“red”); ((Balloon)o2).setColour(“blue”); } }

                                                                                                                              - robert

                                                                                                                              JournalDev
                                                                                                                              DigitalOcean Employee
                                                                                                                              DigitalOcean Employee badge
                                                                                                                              October 27, 2018

                                                                                                                              package headfirst.designpatterns.adapter.ducks; public class PassbyValueExample { public static void main(String args[]) { Balloon red = new Balloon(“red”); Balloon blue = new Balloon(“blue”); swap(red, blue); System.out.println("ex1. red colour = " + red.getColour()); System.out.println("ex1. blue colour = " + blue.getColour()); System.out.println(); swap2(red, blue); System.out.println(); System.out.println("ex2. red colour = " + red.getColour()); System.out.println("ex2. blue colour = " + blue.getColour()); } private static void swap(Object o1, Object o2) { Object temp = o1; o1 = o2; o2 = temp; } private static void swap2(Object o1, Object o2) { // Object temp = o1; // o1 = o2; // o2 = temp; // o1 and o2 are copies of red and blue objects and these copies sent as values // and hence Pass by value // So in caller method swap2(red, blue), red and blue are references to actual // objects created in heap and in called method(current method) o1 and o2 are // copies of the red and blue which point to same object in heap // As o1 and o2 are also references for actual objects you can modify object // like below ((Balloon) o1).setColour(“blue”); ((Balloon) o2).setColour(“red”); // After below 2 statements o1 and o2 pointing to new objects in heap memory. o1 = new Balloon(“red”); o2 = new Balloon(“blue”); System.out.println("ex2. red colour = " + ((Balloon) o1).getColour()); System.out.println("ex2. blue colour = " + ((Balloon) o2).getColour()); /* * The above change only effect in current method as o1 and o2 scope is only in * swap2 method and after swap2 method finished jvm only know red and blue * references which still point to old objects If Java is Pass by reference then * after swap2 call o1 and o2 color should be red and blue. */ } }

                                                                                                                              - Satish

                                                                                                                                JournalDev
                                                                                                                                DigitalOcean Employee
                                                                                                                                DigitalOcean Employee badge
                                                                                                                                October 2, 2018

                                                                                                                                Java is pass by value ok but careful : if you pass an Object as parameter you are passing the reference to it. So whatever you do with your parameter inside the method will actually modify the Object passed. Of course the reference will not be changed.

                                                                                                                                - Noe

                                                                                                                                JournalDev
                                                                                                                                DigitalOcean Employee
                                                                                                                                DigitalOcean Employee badge
                                                                                                                                October 29, 2018

                                                                                                                                You’re still passing a value (copy) of the reference, NOT the reference itself. You can assign new object to that copied reference and outter reference will still point to the old object!

                                                                                                                                - mp77

                                                                                                                                  JournalDev
                                                                                                                                  DigitalOcean Employee
                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                  December 26, 2018

                                                                                                                                  Can you explain the array behaviour here : public class PassByValueTest { public static void main(String[] args) { PassByValueTest p = new PassByValueTest(); p.start(); } private void start() { long[] a1 = { 3, 4, 5}; long[] a2 = fix(a1); System.out.println(a1[0]+" “+a1[1]+” “+a1[2]+” “); System.out.println(a2[0]+” “+a2[1]+” “+a2[2]); boolean b1 = false; boolean b2 = fix(b1); System.out.println(b1+” “+b2); int a = 5; int b = fix(a); System.out.println(a+” "+b); } private int fix(int c) { c=7; return c; } private boolean fix(boolean b1) { b1 = true; return b1; } private long[] fix(long[] a3) { a3[1] = 7; return a3; } } output : 3 7 5 3 7 5 false true 5 7 according to pass by value concept first line should be 3 4 5 kindly explain this behaviour.

                                                                                                                                  - Mayank Kumar

                                                                                                                                  JournalDev
                                                                                                                                  DigitalOcean Employee
                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                  May 17, 2019

                                                                                                                                  In Java, all primitives like int, char, etc are similar to C/C++, but all non-primitives (or objects of any class) are always references. So it gets tricky when we pass object references to methods. Java creates a copy of references and pass it to method, but they still point to same memory reference. Mean if set some other object to reference passed inside method, the object from calling method as well its reference will remain unaffected.

                                                                                                                                  - Anonymous

                                                                                                                                    JournalDev
                                                                                                                                    DigitalOcean Employee
                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                    January 2, 2019

                                                                                                                                    I think a lot of the confusion stems from the verbiage. Expressions like, “pass by value” and “pass by reference” lead people to think we are, “passing the value” and “passing the reference”, respectively. It’s clearer to simply say, “we are not passing the value or the reference, we are passing a NEW reference to the same value.”

                                                                                                                                    - Rob

                                                                                                                                    JournalDev
                                                                                                                                    DigitalOcean Employee
                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                    January 31, 2019

                                                                                                                                    Excellent summary. Thank you. Adds to the video explanation, which I found very good.

                                                                                                                                    - Curious George

                                                                                                                                      JournalDev
                                                                                                                                      DigitalOcean Employee
                                                                                                                                      DigitalOcean Employee badge
                                                                                                                                      January 8, 2019

                                                                                                                                      I think it’s wrong , just swap reference address object

                                                                                                                                      - alireza alallah

                                                                                                                                        JournalDev
                                                                                                                                        DigitalOcean Employee
                                                                                                                                        DigitalOcean Employee badge
                                                                                                                                        January 30, 2019

                                                                                                                                        Hi thanks for your work. It’s very good. Around minute 7:50, though, could you have just erased blue’s arrow and redrawn it pointing to red, or did you intentionally change the box from blue to red?

                                                                                                                                        - Curious George

                                                                                                                                          JournalDev
                                                                                                                                          DigitalOcean Employee
                                                                                                                                          DigitalOcean Employee badge
                                                                                                                                          January 30, 2019

                                                                                                                                          Sorry, minute 6:40, not 7:45.

                                                                                                                                          - Curious George

                                                                                                                                          JournalDev
                                                                                                                                          DigitalOcean Employee
                                                                                                                                          DigitalOcean Employee badge
                                                                                                                                          January 30, 2019

                                                                                                                                          If you think in terms of String Pool, then yes I should just point it to Red object. However, I wanted to keep it simple and not mix the string pool concept with pass by value concept. It could have been any other type of custom object too.

                                                                                                                                          - Pankaj

                                                                                                                                            JournalDev
                                                                                                                                            DigitalOcean Employee
                                                                                                                                            DigitalOcean Employee badge
                                                                                                                                            February 20, 2019

                                                                                                                                            If Java is pass by value and not reference, how come Collection.sort(ArrayListName) sorts the collection object, when we are not re-assigning the value to original object? We are just calling sort method with reference of collection.

                                                                                                                                            - Rajat Mehla

                                                                                                                                            JournalDev
                                                                                                                                            DigitalOcean Employee
                                                                                                                                            DigitalOcean Employee badge
                                                                                                                                            May 5, 2019

                                                                                                                                            We are not re-assigning it, but check the sort() method in Collection. It is re-assigning.

                                                                                                                                            - Shervin

                                                                                                                                              JournalDev
                                                                                                                                              DigitalOcean Employee
                                                                                                                                              DigitalOcean Employee badge
                                                                                                                                              March 26, 2019

                                                                                                                                              I think a C programmer will easily understand this. If we want to swap pointers, we need to pass the pointer of pointers. *p If we want to swap values, we need to pass the pointer of values. *val

                                                                                                                                              - Wagner

                                                                                                                                                JournalDev
                                                                                                                                                DigitalOcean Employee
                                                                                                                                                DigitalOcean Employee badge
                                                                                                                                                April 24, 2019

                                                                                                                                                This article achieved an almost impossible feast. Turning muddy water into mud. I’m kidding. :-) You assume 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. By doing so you confuse me and all these many people. But I want to thank you anyway ! First because you incited me to write this answer: https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value/55831416#55831416 And second because I like your articles very much.

                                                                                                                                                - Stephane

                                                                                                                                                  JournalDev
                                                                                                                                                  DigitalOcean Employee
                                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                                  April 25, 2019

                                                                                                                                                  This article is good if you have some previous understanding of Java passing. Basically, you proved nothing here. Why? Well, you said that Java is passed by value, not by ref. But in the case of swap(), you are passing object reference. And the reason why swapping is not successful is because you did all the swap thing inside of the method which basically didn’t have any effect on base objects. You were just switching memory location inside a method by adding it to a temp object variable. Real switch/update of the object you did within the foo method by updating ballon from blue to red. Please, don’t confuse us :) Primitive types are passed by value but objects are pass by reference.

                                                                                                                                                  - Nikola

                                                                                                                                                    JournalDev
                                                                                                                                                    DigitalOcean Employee
                                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                                    May 14, 2019

                                                                                                                                                    Great !! red color in o1=Blue blue color in o2=Red red color=Red blue color=Blue blue color=Red This output would have cleared the confusion more effectively.

                                                                                                                                                    - Akash

                                                                                                                                                      JournalDev
                                                                                                                                                      DigitalOcean Employee
                                                                                                                                                      DigitalOcean Employee badge
                                                                                                                                                      May 17, 2019

                                                                                                                                                      I totally disagree with this article. Java is pass by reference that’s why we are unable to swap two objects. Reference is a pointer when you assign a new object to it then the reference starts pointing to the new object. and you can’t change the original object. In the foo function, color is changed to red and in the main function, color red is printed. Because the object was passed by reference. You can never explain how this can happen in call by value.

                                                                                                                                                      - Java Developer

                                                                                                                                                      JournalDev
                                                                                                                                                      DigitalOcean Employee
                                                                                                                                                      DigitalOcean Employee badge
                                                                                                                                                      September 13, 2019

                                                                                                                                                      A reference is not a pointer. A pointer is a type. A reference is alias to an l-value which cannot be null or changed.

                                                                                                                                                      - ComputerScientist

                                                                                                                                                        JournalDev
                                                                                                                                                        DigitalOcean Employee
                                                                                                                                                        DigitalOcean Employee badge
                                                                                                                                                        May 20, 2019

                                                                                                                                                        The reference of the object is passed by value

                                                                                                                                                        - patient-zero

                                                                                                                                                          JournalDev
                                                                                                                                                          DigitalOcean Employee
                                                                                                                                                          DigitalOcean Employee badge
                                                                                                                                                          May 27, 2019

                                                                                                                                                          It is a good interview queston if you are talking with a senior programmer who knows multiple languages and understands the Pascal / C terminology. On other side, if you talk with a pure Java programmer, it is rather an evil catch, because Java (misuses) the term “reference” for something which in Pascal / C corresponds with (but is not equivalent to) “pointer”. The correct answer is e.g. here https://stackoverflow.com/a/40523/2886891 and the exact wording should be like this > Java is always pass-by-value. When we pass the value of an object, we are passing the reference to it.

                                                                                                                                                          - Honza Zidek

                                                                                                                                                            JournalDev
                                                                                                                                                            DigitalOcean Employee
                                                                                                                                                            DigitalOcean Employee badge
                                                                                                                                                            June 16, 2019

                                                                                                                                                            Thank you for this explanation and the video. I am an electrical engineering student, but take computer science classes as part of my curriculum. My professor taught us Java was pass-by-value, and our textbook said the same but I found those explanations a little confusing because the net effect of some methods really seem to be pass-by-reference based on my understanding of it. Your foo method is a good example of this. However, after reading your article, my class notes, and the relative sections in my book many times, I am finally starting to understand. Also, your video was exceptionally helpful by going over stack and heap memory. When it clicked for me is when I realized the value stored in the reference variable (which has its own memory address) is the memory address of the object. Therefore, the value passed to a method is a copy of the object’s memory address. Though a method can mutate the object at the received memory address, it cannot mutate the value of the address stored in the original reference variable, and so the language is pass-by-value. Thanks again!

                                                                                                                                                            - Electrical Engineering Student

                                                                                                                                                              JournalDev
                                                                                                                                                              DigitalOcean Employee
                                                                                                                                                              DigitalOcean Employee badge
                                                                                                                                                              June 18, 2019

                                                                                                                                                              thanks !!! that settled my doubts

                                                                                                                                                              - baozi

                                                                                                                                                                JournalDev
                                                                                                                                                                DigitalOcean Employee
                                                                                                                                                                DigitalOcean Employee badge
                                                                                                                                                                July 2, 2019

                                                                                                                                                                I think it is perfect explanation…My concept is cleared…!!! It is just that a new reference copied reference variable is passed in the arguments…

                                                                                                                                                                - Vivek

                                                                                                                                                                  JournalDev
                                                                                                                                                                  DigitalOcean Employee
                                                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                                                  July 25, 2019

                                                                                                                                                                  Try this modified swap function: public static void swap(Balloon balloon, Balloon balloon2){ Balloon temp = balloon; balloon.setColor(balloon2.getColor()); balloon2.setColor(temp.getColor()); } for more confusion :)

                                                                                                                                                                  - Dim Gab

                                                                                                                                                                    JournalDev
                                                                                                                                                                    DigitalOcean Employee
                                                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                                                    August 5, 2019

                                                                                                                                                                    Pass by reference is actually possible in Java though. If for example, you have a method that takes an interface like this. public static void passByRefExample(List foo) { foo.add(“bar”); } And then you invoke it using an object with allocated heap space. Like so. public static void main(String[] args) { List foo = new ArrayList(); foo.add(“foo”); passByRefExample(foo); foo.stream().forEach(bar -> System.out.println(bar)); } output: foo bar

                                                                                                                                                                    - Jonathan

                                                                                                                                                                      JournalDev
                                                                                                                                                                      DigitalOcean Employee
                                                                                                                                                                      DigitalOcean Employee badge
                                                                                                                                                                      September 26, 2019

                                                                                                                                                                      I understand how Java is passing the parameters but I don’t agree that it is passing by value. Look at your definition: “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.” That is exactly what Java does. It is coping a reference to object and placing a copy on a stack memory with other parameters. There is no deep copy of the object itself (which we usually name as Pass by value). In C++ you can also pass by pointer. The pointer is copied to the stack as any other parameters of the method. The fact that we copy value of the pointer does not mean that we pass parameter by value.

                                                                                                                                                                      - Paweł

                                                                                                                                                                        JournalDev
                                                                                                                                                                        DigitalOcean Employee
                                                                                                                                                                        DigitalOcean Employee badge
                                                                                                                                                                        October 25, 2019

                                                                                                                                                                        If you say Java is pass by value, you must base it against a lanuage like C++ where the definition is widely accepted, nuanced, and understood. When you create your balloons in your sample Java code, you are: - creating a pointer on the stack, which points to an object on the heap. - creating a new frame upon calling the swap method, which copies the object arguments (pointers) into it’s own stack space. note now our heap address is copied inside both the main stack frame and the swap stack frame. - reassign the swap stack frame’s local variables and their contents You can do the same thing in C++: - create a pointer on the stack, pointing to memory on the heap: Balloon * red = new Balloon(“red”); Balloon * blue = new Balloon(“blue”); swap(red, blue); - creating a new stack in the swap method, which copies the object arguments (pointers) into it’s own stack space swap(Balloon * r, Ballon * b) { Balloon * temp = r; r = b; b = temp; } - in c++, you can print out specific memory addresses. If you did so in the main method, you’d find that red and blue would be low heap addresses, 0x0235897 for example. If you dereference, &red and &blue, you’d find they’re high stack addresses, 0x7ffff235 for example. In the swap method, r and b are copy constructored so while r and b do refer to the same low heap addresses as red and blue, &r and &b are different addresses in the stack as they’re not in the same stack as the original, nor are they the same pointer (like in pass by reference). So really, if you’re using pass-by-value, pass-by-reference, pass-by-pointer terminology the way C++ does, java is pass by pointer for objects, and pass by value for primitives.

                                                                                                                                                                        - Jeff

                                                                                                                                                                          JournalDev
                                                                                                                                                                          DigitalOcean Employee
                                                                                                                                                                          DigitalOcean Employee badge
                                                                                                                                                                          November 9, 2019

                                                                                                                                                                          I think the confusion is about relativity. If you look at the object, then we can say it is passed by reference. If you look at the variable, then we can say it is passed by value (whatever it is, being an int, float or a reference towards an object). Method arguments are local variables anyways, of course they are passed by value. It is important to define the “what” that is passed to a method first. Seems evident to someone who got the subtility, not to target audience. It is not about Java vs C/C++, it is the same passing behaviour. The only difference is that in C/C++, you can have object variables and not only references towards objects, meaning that you pass an object by value. But a pointer or reference stays a variable which is passed by value, even if you use a pointer to a pointer to … to an object.

                                                                                                                                                                          - someone

                                                                                                                                                                            JournalDev
                                                                                                                                                                            DigitalOcean Employee
                                                                                                                                                                            DigitalOcean Employee badge
                                                                                                                                                                            December 16, 2019

                                                                                                                                                                            this article causes more confusion than explain anything clearly at all… :))) you say objects are copied before passed down? thats wrong… object are not, but their references are copied, objects stays the same that means, one can not dereference variable inside method because its a copy, BUT, and thats a big BUT that same copy points to same object as original reference so if you modified object it will be modified everywhere its used.

                                                                                                                                                                            - levan

                                                                                                                                                                              JournalDev
                                                                                                                                                                              DigitalOcean Employee
                                                                                                                                                                              DigitalOcean Employee badge
                                                                                                                                                                              December 31, 2019

                                                                                                                                                                              This is awesome blog and i have increased my knowledge regarding java from this, thank you very much for writing this. Keep writing.

                                                                                                                                                                              - Ronak Vora

                                                                                                                                                                                JournalDev
                                                                                                                                                                                DigitalOcean Employee
                                                                                                                                                                                DigitalOcean Employee badge
                                                                                                                                                                                January 26, 2020

                                                                                                                                                                                if you have an array it is Pass by Reference … “Java is always Pass by Value” … seems to be wrong

                                                                                                                                                                                - Senecaek2

                                                                                                                                                                                  JournalDev
                                                                                                                                                                                  DigitalOcean Employee
                                                                                                                                                                                  DigitalOcean Employee badge
                                                                                                                                                                                  February 1, 2020

                                                                                                                                                                                  thanks for sharing, explanation is very clear.

                                                                                                                                                                                  - kamlesh parmar

                                                                                                                                                                                    JournalDev
                                                                                                                                                                                    DigitalOcean Employee
                                                                                                                                                                                    DigitalOcean Employee badge
                                                                                                                                                                                    March 8, 2020

                                                                                                                                                                                    You have clearly given the addresses copied in the function parameters too which is same as the called time address value. Hence, its passed by reference only. If it is passed by value, the value alone will be copied and the address will not be the same. Hence, the foo(Balloon balloon) function first line will not work if it copied by value alone. Since, it’s pass by reference, the modification happened on the location from ‘Blue’ to ‘Red’ reflected in the main() function where it is called. { Balloon red = new Balloon(“Red”); //memory reference 50 Balloon blue = new Balloon(“Blue”); //memory reference 100 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 } The problem here is, since the Java is not clear in call by reference (not exactly the pointer, the real method of handling the objects through addresses like in C & CPP) and pass by value, the new address assigned is not getting reflect in the called time variable’s / object’s address. Where it failed to copy/update the new address assigned in the called function to the original address. Somehow it seems like bug but, its the design actually and if you need to get the new addressed value, you have to get it on return value and assign in the calling area.

                                                                                                                                                                                    - B Senthil Kumaran

                                                                                                                                                                                      JournalDev
                                                                                                                                                                                      DigitalOcean Employee
                                                                                                                                                                                      DigitalOcean Employee badge
                                                                                                                                                                                      March 23, 2020

                                                                                                                                                                                      public static void swap(Object o1, Object o2){ Object temp = o1; o1=o2; o2=temp; } o1 and o2 are local variables inside of the swap method’s scope. You just swapped the value of two local variables, why would it cause effect on the objects itself? You didn’t do anything with the 2 object.

                                                                                                                                                                                      - bb

                                                                                                                                                                                        JournalDev
                                                                                                                                                                                        DigitalOcean Employee
                                                                                                                                                                                        DigitalOcean Employee badge
                                                                                                                                                                                        March 25, 2020

                                                                                                                                                                                        I think you are wrong, Method parameters stores reference addresses. How can you call it pass by value while it is storing references.

                                                                                                                                                                                        - Zeynel

                                                                                                                                                                                          JournalDev
                                                                                                                                                                                          DigitalOcean Employee
                                                                                                                                                                                          DigitalOcean Employee badge
                                                                                                                                                                                          May 7, 2020

                                                                                                                                                                                          i think this is inaccurate statement, the ‘pass by value’ in java not always fall into your definition, for example, array, when you pass the array into a function it the copy of the reference to the underlying array that is passed into the function. so if you change the array the change is going to be reflected outside of the function call as well.

                                                                                                                                                                                          - Zhe

                                                                                                                                                                                            JournalDev
                                                                                                                                                                                            DigitalOcean Employee
                                                                                                                                                                                            DigitalOcean Employee badge
                                                                                                                                                                                            September 14, 2020

                                                                                                                                                                                            “Java is always Pass by Value and not pass by reference, we can prove it with a simple example” - totally WRONG! If java is “always Pass by Value” then when you pass an object to a method, you should have an ENTIRE COPY OF THAT OBJECT - as it happens in C++, and the method should operate solely on that COPY, not on the original! Objects in java are ALWAYS PASSED BY REFERENCE(which technique always uses a copy of the address where the original variable points to - people are confounding this with pass-by-value) the “swap” example is totally irrelevant as it doesn’t deal with “pass by reference” in any way, but it relies on the ability of a variable to point to another variable name, which is not permitted in java

                                                                                                                                                                                            - ccdan

                                                                                                                                                                                              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.