关于java常用的内存理解

    int[] arr = new int[4];  // 内存图如下

这里写图片描述

理解: 凡是new关键字创建的对象,jvm都会在堆内存中开辟新的空间创建一个新的对象。
所以对于上述的=相当于把数组对象内存地址赋值给arr变量。

    int[] arr1 = new int[2];
    int[] arr2 = arr1;   // 公用一个内存地址,所以下面的操作arr1和arr2指向同一个堆内存地址
    arr1[1]=10;
    arr2[1]=20;

    arr1[1] = 20;

这里写图片描述

    // 二维数组
    int[][] arr = new int[3][4];

这里写图片描述

class Student{
    String name;

    // 使用static修饰country,那么这时候country就是一个共享的数据
    static String country = "China"; 
    // 在这个位置使用了static的区别, 这个数据就不会存在对象堆内存中维护了,而是存放到了数据共存去来维护。这是最关键的区别...  在内存中的表现如下图..
    // String country = "China";  这种情况的country成员变量是存放在堆内存的位置中,所以有没有static是完全不同的两种格式

    // 构造函数
    public Student(String name) {
        this.name = name;
        this.country = country;
    }

}

class Demo9 {
    public static void main(String[] args) {
        Student s1 = new Student("GOD");
        Student s2 = new Student("PIG");
        }
    }

这里写图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章