Basic
In this topic, the most important thing is to make primitive and reference value clear.
1 | int i = 1; |
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 | static void test(int i, String str){ |
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 | static void test(int i, StringBuilder str){ |
StringBuilder is an object with string manipulations. When Java passes it into test method, its reference address is still the same.
Note
JVM中,所有对象都是在堆中分配内存空间的,栈只用于保存局部变量和临时变量,如果是对象,只保存引用,实际内存还是在堆中。