案例:常量池
public class StringDemo5 {
public static void main(String[] args) {
// ==和equals方法的区别
//定义三个字符串,内容都是study
String str1="study";
String str2="study";
String str3=new String("study");
System.out.println("str1和str2的内容相同?"+(str1.equals(str2)));
System.out.println("str1和str3的内容相同?"+(str1.equals(str3)));
System.out.println("str1和str2的地址相同?"+(str1==str2));
System.out.println("str1和str3的地址相同?"+(str1==str3));
}
}
运行结果:
str1和str2的内容相同?true
str1和str3的内容相同?true
str1和str2的地址相同?true
str1和str3的地址相同?false
字符串的不可变性
String的不可变性:String对象一旦被创建,则不能修改,是不可变的,所谓的修改其实是创建类新的对象,所指向的内存空间不变。
案例:
public class StringDemo6 {
public static void main(String[] args) {
//String的不可变性
//String对象一旦被创建,则不能修改,是不可变的
//所谓的修改其实是创建了新的对象,所指向的内存空间不变
String s1="study";
String s2="hello,"+s1;
//s1不再指向study所在的内存空间,而是指向了"hello,study"
//String s1="hello,"+s1;
System.out.println("s1="+s1);
System.out.println("s2="+s2);
String s3=new String("hello,study!");
System.out.println("子串:"+s3.substring(0,5));
System.out.println("s3="+s3);
}
}
运行结果:
s1=study
s2=hello,study
子串:hello
s3=hello,study!
![](https://i-blog.csdnimg.cn/blog_migrate/0505033fe9c3d61c7aa1d11170be6bf9.png#pic_center)
![](https://i-blog.csdnimg.cn/blog_migrate/b8a6cddfcf85017d6c8dba8ddf7d4295.png#pic_center)
![](https://i-blog.csdnimg.cn/blog_migrate/db2a8e6bd4fbbf31ba14fa7e2c31b58e.png#pic_center)