0%

JavaSE passing data among methods

Basic

In this topic, the most important thing is to make primitive and reference value clear.

1
2
int i = 1;
String str = “Allen”

What are they like in the memory?

  • primitive

  • reference

1
str = "Java"
  • reference

Actually, they are all values. Primitive holds the value itself, while reference refers to address value.

Now let’s see some examples.

Example 1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
static void test(int i, String str){
i = 1;
str += "1";
System.out.println(str.hashCode());
}

public static void main(String[] args){
int i = 11;
String str = "Allen";
System.out.println(str.hashCode());

test(i, str);
System.out.println(i);
System.out.println(str);
}

Result:
63353322
1963953031
11
Allen

Explain
i and str are primitive type, so Java passes them as value copies into the method.
Observe the hashcode, string inside and outside test method
are not the same.
  • str in main method

  • str in test method

    Before str execute +=, it points to “Allen”. While doing +=, “Allen” cannot be changed in heap, so Java has to get a new memory block to hold “Allen1” in heap. Eventually, variable str’s hold a new address value 0x45 pointing to “Allen1”.
    Additionally, when Java passes it into method, the variable str with reference address 0x34 is copied into the variable in the test method, which is called passing data by value in Java. Address or value itself are regarded as value in general, which is the most important to make sense in this topic.

Example 2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
static void test(int i, StringBuilder str){
i = 1;
str.append("1");
System.out.println(str.hashCode());
}

public static void main(String[] args){
int i = 11;
StringBuilder str = new StringBuilder("Allen");
System.out.println(str.hashCode());

test(i, str);
System.out.println(i);
System.out.println(str);
}

Result:
1625635731
1625635731
11
Allen1

Explain
Here str is object not primitive, so pass a copy into the method.
Observe the hashcode, same.

StringBuilder is an object with string manipulations. When Java passes it into test method, its reference address is still the same.

Note

JVM中,所有对象都是在堆中分配内存空间的,栈只用于保存局部变量和临时变量,如果是对象,只保存引用,实际内存还是在堆中。