先看代码:

String s = "hello world";
String s0 = "hello world";
String s1 = new String("hello world");
String s2 = new String("hello world").intern();
System.out.println(s==s0); //true
System.out.println(s==s1); //false
System.out.println(s==s2); //true
System.out.println(s1==s2); //false

运行结果:

true
false
true
false

通过阅读intern()方法的源码,intern()方法是一个native方法,native不是由java编写的,而是由jvm根据各个平台实现的本地方法,但是通过注释可以看到相关描述。

所以有个字符串池(不知道是不是这么叫,我乱起的)来保存字符串常量,而通过new String()方法创建的的字符串对象是重新在堆中分配了一块地址,所以s==s1是false,通过调用intern()方法,如果字符串中有相同的字符串(equals()为true)则返回字符串池中的引用,如果没有则将当前对象添加到字符串池中并返回当前对象的引用。