``## 字符串池
一. 作为最常用的对象之一,所以有时候会出现多个重复的字符串,为了节省内存,所以引入的“字符串池”的设计,这样可以重复利用字符串。
二. 关于字符串池的几点描述:
1.字符串池位于堆内存当中的一小块空间,用来保存若干个字符串的地址值;
2.字符串池当中绝对不会出现重复的字符串所对应的地址;
3.凡是直接双引号的字符串默认在池中,而new出来的字符串默认不在池中;
ps:对于基本类型来说;“==”是进行数据内容的相同比较,而对于引用类型来说,则是进行地址值的相同比较
如果是两个对象,其地址值必然不同,如果地址值相同,必然是同一个对象。
String str1 = "hello";
String str2 = "hello";
System.out.println(str1 == str2);//true
char[] array = {'h','e','l','l','o'};
String str3 = new String(array);
String str4 = new String(array);
System.out.println(str3 == str4);//false
上述代码的内存图解
三,字符串创建的常见2+1种方式(两种构造方法,一种直接复制)
1.两种构造方法
(1)public String(char[] array),参数是一个字符数组,根据字符数组的内容创建一个字符串
(2)public String(char[] array,int offset, int count),根据字符数组的一部分内容创建字符串
参数 offset 代表字符数组的起始索引(从0开始);
参数 count 代表取用多少个字符;
2.用双引号直接赋值
char[] array = {'h','e','l','l','o'};
//创建对象的语法格式: 类名称 对象名 = new 类名称(构造参数);
String str1 = new String(array);
String str2 = new String(array,1,3);
String str3 = "hello word!";
System.out.println(str1);//hello
System.out.println(str2);//ell
System.out.println(str3);//hello word!