一、String 的特性
1、String声明为final的,不可被继承。
2、String实现了Serializable接口:表示字符串是支持序列化的。
实现了Comparable接口:表示String 可以比较大小。
3、String 内部定义了final char[ ] value用于存储字符串数据。
4、String代表不可变的字符串序列。具有不可变性。
体现:1、当字符串重新赋值时,需要重新指定内存区域赋值。不能使用原有的value进行赋值。
2、当现有的字符串进行连接操作时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
3、当String的replace()方法修改指定字符或字符串时,也需要重新指定内存区域赋值,不能使用原有的value进行赋值。
5、通过字面量的方式(区别于new)给一个字符串赋值,此时字符串值声明在字符串常量池中。
6、字符串常量池中是不会存储相同的字符串的。
@Test
public void test1() {
String s1 = "abc";
System.out.println("s1地址值: " + s1.hashCode());//s1地址值: 96354
String s2 = "abc";
System.out.println("s2地址值: " + s2.hashCode());//s2地址值: 96354
s1 = "hello";
System.out.println("s1地址值: " + s1.hashCode());//s1地址值: 99162322
System.out.println(s1);//hello
System.out.println(s2);//abc
System.out.println(s1 == s2);//false
}
![](https://i-blog.csdnimg.cn/blog_migrate/a569f19a3bd37263f6d5e1dd22563ec8.jpeg)
7、String 的实例化的方式:
1、方式一:通过字面量定义的方式。此时数据在方法区的字符串常量池中。
2、方式二:通过new + 构造器的方式。此时对象保存的是地址值,是数据在堆空间中开辟空间以后对应的地址值,堆空间存的是数据在常量池的地址值。
@Test
public void test2() {
// 通过字面量的方式:此时s1和s2的数据JavaEE在方法区的字符串常量池中。
String s1 = "JavaEE";
String s2 = "JavaEE";
// 通过new + 构造器的方式:此时的s3和s4保存的地址值,是数据在堆空间中开辟空间以后对应的地址值。
String s3 = new String("JavaEE");
String s4 = new String("JavaEE");
System.out.println(s1 == s2);//true
System.out.println(s1 == s3);//false
System.out.println(s1 == s4);//false
System.out.println(s3 == s4);//false
}
![](https://i-blog.csdnimg.cn/blog_migrate/9487673d63eb2c96f25f38a8eb7d3ded.jpeg)
8、常量与常量的拼接,结果在堆空间。且常量池不会存在相同内容的常量。
9、拼接时只要其中有一个是变量,结果就会存在堆空间里。
10、intren( )方法的返回值,永远都在常量池中。
@Test
public void test3(){
String s1 = "java";
String s2 = "Spring";
String s3 = "javaSpring";
String s4 = "java" + "Spring";
//拼接内容含有对象的,会存在堆空间
String s5 = s1 + "Spring";
String s6 = "java" + s2;
String s7 = s1 + s2;
String s8 =(s1 + s2).intern();
System.out.println(s3 == s4);//true
System.out.println(s3 == s5);//false
System.out.println(s3 == s6);//false
System.out.println(s3 == s7);//false
System.out.println(s5 == s6);//false
System.out.println(s5 == s7);//false
System.out.println(s3 == s8);//true
}
![](https://i-blog.csdnimg.cn/blog_migrate/e7a132487fd624f36d8563fc0e613593.png)