不同于C/C++的内存四区,Java有自己的内存管理模型,而本文将介绍一部分有关内存的问题。

new关键字

new关键字是在堆区开辟出一块内存用于储存数据。
所有通过new关键字而创建出来的都被储存在堆区。
对于同一个字符串phil616

  1. String str1 = new String("phil616");
  2. String str2 = "phil616"

二者一个是在公共池中创建,一个是在堆区创建,所以使用逻辑运算符 == 判断二者是否相等是不正确的。
因为一个是属性,而另一个是对象。二者的本质不同。

static关键字

static表示在内存中只有一份。
如果两个对象共用一个static变量或方法,那么这个所有使用这个static变量的对象都会更改。
也就是说,我虽然使用同一个类创建了两个对象,但是对象使用的是同一个static属性,如果上一个对象对static属性进行更改,那么下一个也会跟着更改。因为二者公用一份内存,公用同一个变量。
但是这样的好处是大大节省了内存开销。尤其是工具类方法,例如get或set,可以大大节省内存。

  1. package com.yuque.phil616.memorys;
  2. public class MainDemo {
  3. /*
  4. * key word 'static' means this function/method/variable/property only exits
  5. * one in memory, to understand the meaning of memory, we need to know what
  6. * does the memory consist.
  7. * There are four areas in memory
  8. * heap and thread stack. we don't need to know what are them for now.
  9. * however, static means there are only one copy of it in memory.
  10. * */
  11. public static void main(String[] args) {
  12. Mer m1 = new Mer();
  13. Mer m2 = new Mer();
  14. m1.setI(5);
  15. m2.setI(10);
  16. System.out.println(m1.getI());
  17. System.out.println(m2.getI());
  18. /*
  19. * We can find out that they are both 10, because they are using a same
  20. * block to storage i. in this case, after I set i by 5, the value of i
  21. * changed into 5, and I set i by 10, it have changed into 10;
  22. * */
  23. }
  24. /*
  25. * for example, this variable/property i ara static, means there are only one
  26. * space to stored this variable.
  27. * */
  28. static int i = 10;
  29. //If you want to understand more about memory in C/C++
  30. //Please access passage https://zhuanlan.zhihu.com/p/350301516
  31. }
  32. class Mer{
  33. static int i;
  34. /*
  35. * as the same reason, if a method of function is using like a tool,
  36. * just modify them to a static method, this made objects smaller.
  37. * */
  38. public static void setI(int i) {
  39. Mer.i = i;
  40. }
  41. public static int getI() {
  42. return i;
  43. }
  44. }