Yet Another “Java Passes By Reference or By Value”?

This is a classic interview question which confuses novice Java developers. In this post I will use an example and some diagram to demonstrate that: Java is pass-by-value.

1. Some Definitions

Pass by value: make a copy in memory of the actual parameter's value that is passed in.
Pass by reference: pass a copy of the address of the actual parameter.

Java is always pass-by-value. Primitive data types and object reference are just values.

2. Passing Primitive Type Variable

Since Java is pass-by-value, it's not hard to understand the following code will not swap anything.

swap(Type arg1, Type arg2) {
    Type temp = arg1;
    arg1 = arg2;
    arg2 = temp;

3. Passing Object Variable

Java manipulates objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference, but by value.

Question is: why the member value of the object can get changed?



class Apple {
	public String color="red";
public class Main {
	public static void main(String[] args) {
		Apple apple = new Apple();
	public static void changeApple(Apple apple){
		apple.color = "green";

Since the orignal and copied reference refer the same object, the member value gets changed.


Category >> Basics  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • Weijie Huang

    what is the difference between that one and this post?

  • When we say

    A a = new A();

    The new operator allocates memory for the created object and returns a reference to that memory which is then assigned to the variable of the class type.
    So, it can be said “a” is a variable which is holding a value and that value happens to be the reference to the memory address. So even for object it is pass by value.
    Please see the post to know more –

  • sfdgsdf

    YES, but values are not necessarily references, think about it before posting, thanks.

  • 薛保锋

    object reference are just values, so it’s pass by reference.