What are the two data types of Java?
Data types in Java fall into two main categories: value types (base data types) and reference types (composite data types)
One: Value type:
Integer type (byte,short,int,long) floating-point type (float,double) Boolean type (Boolean) character type (char)
Two: Reference value type:
In addition to value types, reference value types have class type (Class) array interface types (interface)
Difference between a value type and a reference type
Value passing and reference passing
The assignment of the base data type is a value pass, the value type variable A is assigned to the value type variable B, and then the value of a is changed so that B does not change with a.
a=1;int b=a;a=2;System.out.println("a:"+a+"b:"+b);
The assignment of a reference value type is a reference pass, passing the reference address of the object. When a reference value type variable A is assigned to a reference value type variable B, and then changes the value of a, then B changes as a changes.
PublicClasstest () {int num; public test (int num) {this.num=num; } public void steNum (int num" {this.num=num;} public static void main (String args[]) {test ta= new Test (1); Test tb= new test (); tb=ta; Ta.setnum (2); System. out.println ( "TA:" +ta.num+ "TB:" + Tb.num); }}
2 Memory allocation
This behavior occurs because the value type data and the reference type data are not in the same memory allocation in Java.
Value type data is stored directly in the stack, and the Java JVM opens up a space in the stack to directly store the value of the data.
a=1; //JVM为变量a在栈中开辟了一块空间(假设为A),栈中存储的是 1;int b=a; //JVM为变量b在栈中开辟另了一块空间(假设为B),栈中存储的也是 1; a=2; //为变量a重新赋值,栈空间A中存储的值改为2,栈空间B中存储的值不变为1
Reference type data is not stored directly in the stack, and the Java JVM allocates memory space to the data in the heap, and the heap stores the data. The stack stores the address that points to the corresponding heap. It can be said that the address in the stack refers to the data in the heap.
new Test(1);/* JVM为ta变量在堆中开辟一块空间(假设为K),那么堆空间K存储的是 1;JVM为ta变量在栈中开辟一块空间(假设为A),那么栈空间A存储的是指向堆空间的地址(假设为1000)*/Test tb= new Test(0);/* JVM为tb变量在堆中开辟一块空间(假设为J),那么堆空间J存储的是 0;JVM为ta变量在栈中开辟一块空间(假设为B),那么栈空间B存储的是指向堆空间的地址(假设为2000)*/tb=ta;/*栈空间B中存储的地址从2000改为1000(从指向J改为指向K) 现在ta 和 tb 都引用堆空间K*/ta.setNum(2);/*堆空间K中存储的值改为2 所以ta.num和tb.num 都是2 */
Garbage collection mechanism
When the object stored in the heap space is not pointed to by the address stored in the stack space (when referenced), the object is automatically cleaned out. As mentioned above, the heap space J is originally stored in 0
Test tb= new Test(0);
But
tb=ta;
No longer have addresses pointing to heap space J in the original stored 0,0 will be automatically clear.
Differences between Java value types and reference types