Define variables
int a = 10;
int b = a;
b = 20;
System.out.println("a = " + a); // a = 10
a = 30;
System.out.println("b = " + b); // b = 20
After defining a variable, when assigning a variable to another variable, the storage method in the memory is:
int a;
int b; After
defining variables a and b, they are stored in the stack in the following way . The storage locations of a and b are randomly allocated by the system, which may be discontinuous space.
int b = a;
Assign the value 10 in a to b. At this time, there are values in both a and b.
Changing the value of a will not affect the value of b, and changing the value of b will not affect the value of a
Define the array
int[] arr = new int[]{
10,20,30};
int[] brr = arr;
brr[0] = 20;
System.out.println("a = " + arr[0]); // arr[0] = 20
arr[0] = 30;
System.out.println("b = " + brr[0]); // brr[0] = 30
When defining an array, new opens up memory space in the heap, and the system declares an array name in the stack, and at the same time opens up a memory space in the heap to store the array, and stores the address of the first element in the array name.
int[] brr = arr;
Because brr does not create a new object with new, it just assigns the address stored in the arr variable name to brr, so that the same address as arr is stored in brr. So when the value in arr is modified at this time, the value in brr will also be modified. vice versa.
Define a two-dimensional array
Data type [][] Array name = new data type [m][n];
m:表示这个二维数组有多少个一维数组。
n:表示每一个一维数组的元素有多少个。
E.g:
int arr[][]=new int[3][2];
Summary:
1. Stack: program running, heap: data storage
2. Stack storage method call local variables (such as 8 basic data types byte, boolean, char, short, int, long, float, double, and object references Address), and the heap stores the instance of the object (the object instance created with new)
3. The stack has no GC, and the heap has GC (the full name of GC is garbage collection)
4. The stack is isolated between different threads, and Heap is shared