// Tutorial //

Java is Pass by Value, Not Pass by Reference

Published on August 3, 2022 · Updated on December 6, 2022
Default avatar
By Pankaj
Developer and author at DigitalOcean.
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.

If you’ve enjoyed this tutorial and our broader community, consider checking out our DigitalOcean products which can also help you achieve your development goals.

Learn more here


About the authors
Default avatar
Pankaj

author

Developer and author at DigitalOcean.

Default avatar
Technical Editor

Still looking for an answer?

Was this helpful?

“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

    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

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

      - Zeynel

        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

          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

            thanks for sharing, explanation is very clear.

            - kamlesh parmar

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

              - Senecaek2

                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

                  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

                    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