CSDN话题挑战赛第2期
参赛话题:学习笔记
public static void main(String[] args) {
String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");
String s4 = new String("hello");
System.out.println(s1 == s2); // true
System.out.println(s1 == s3); // false
System.out.println(s3 == s4); // false
}
结果:

上述程序创建方式类似,为什么s1和s2引用的是同一个对象,而s3和s4不是呢?
图解:
Java中的创建的String类 的内容是在字符串常量池中,字符串常池是在堆区中
在常量池中由“ ” 引起来的字符串如果相同,只会存储一份,不会重复的存储,节省了空间
在Java中,比如:1、3.14、“abc” 等等这些字名类型常量会经常频繁的使用到
为了使程序的运行速度更快、更节省内存,Java为8种基本数据类型和String类都提供了常量池
池是程序中用来提升效率的方式,未来还会在学习中遇到各种 “内存池”, “线程池”, “数据库连接池”
intern 方法的作用:该方法的作用是手动将创建的String对象添加到常量池中
intern 是一个native方法,Native方法指:底层使用C++实现的,看不到其实现的源代码
例如: