不同于C/C++的内存四区,Java有自己的内存管理模型,而本文将介绍一部分有关内存的问题。
new关键字
new关键字是在堆区开辟出一块内存用于储存数据。
所有通过new关键字而创建出来的都被储存在堆区。
对于同一个字符串phil616
String str1 = new String("phil616");
String str2 = "phil616"
二者一个是在公共池中创建,一个是在堆区创建,所以使用逻辑运算符 == 判断二者是否相等是不正确的。
因为一个是属性,而另一个是对象。二者的本质不同。
static关键字
static表示在内存中只有一份。
如果两个对象共用一个static变量或方法,那么这个所有使用这个static变量的对象都会更改。
也就是说,我虽然使用同一个类创建了两个对象,但是对象使用的是同一个static属性,如果上一个对象对static属性进行更改,那么下一个也会跟着更改。因为二者公用一份内存,公用同一个变量。
但是这样的好处是大大节省了内存开销。尤其是工具类方法,例如get或set,可以大大节省内存。
package com.yuque.phil616.memorys;
public class MainDemo {
/*
* key word 'static' means this function/method/variable/property only exits
* one in memory, to understand the meaning of memory, we need to know what
* does the memory consist.
* There are four areas in memory
* heap and thread stack. we don't need to know what are them for now.
* however, static means there are only one copy of it in memory.
* */
public static void main(String[] args) {
Mer m1 = new Mer();
Mer m2 = new Mer();
m1.setI(5);
m2.setI(10);
System.out.println(m1.getI());
System.out.println(m2.getI());
/*
* We can find out that they are both 10, because they are using a same
* block to storage i. in this case, after I set i by 5, the value of i
* changed into 5, and I set i by 10, it have changed into 10;
* */
}
/*
* for example, this variable/property i ara static, means there are only one
* space to stored this variable.
* */
static int i = 10;
//If you want to understand more about memory in C/C++
//Please access passage https://zhuanlan.zhihu.com/p/350301516
}
class Mer{
static int i;
/*
* as the same reason, if a method of function is using like a tool,
* just modify them to a static method, this made objects smaller.
* */
public static void setI(int i) {
Mer.i = i;
}
public static int getI() {
return i;
}
}