Java-passes-by-reference-Or-by-value

This is a classic question of Java. Many similar questions have been asked on stackoverflow, and there are a lot of incorrect/incomplete answers. The question is simple if you don’t think too much. But it could be very confusing, if you give more thought to it.

1. A code fragment that is interesting & confusing

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
String x = new String("ab");
change(x);
System.out.println(x);
}

public static void change(String x) {
x = "cd";
}

It prints “ab”.

2.What the code really does?

When the string “ab” is created, Java allocates the amount of memory required to store the string object. Then, the object is assigned to variable x, the variable is actually assigned a reference to the object. This reference is the address of the memory location where the object is stored.

The variable x contains a reference to the string object. x is not a reference itself! It is a variable that stores a reference(memory address).

Java is pass-by-value ONLY. When x is passed to the change() method, a copy of value of x (a reference) is passed. The method change() creates another object “cd” and it has a different reference. It is the variable x that changes its reference(to “cd”), not the reference itself.

The following diagram shows what it really does.

3. conclusion

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

4. one more question

why the member value of the object can get changed?

here is the code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Apple {
public String color="red";
}

public class Main {
public static void main(String[] args) {
Apple apple = new Apple();
System.out.println(apple.color);

changeApple(apple);
System.out.println(apple.color);
}

public static void changeApple(Apple apple){
apple.color = "green";
}
}

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

a same phenomenon will be found in collection situation.