你需要了解两件事
1)
String a = "Bob";
String b = "Bob";
System.out.println(a.equals(b));
System.out.println(a == b);
你怎么想?什么输出?
true
true
这样做了什么?在永久生成内存的字符串池中创建的第一个字符串第二个字符串从池中获取现有对象.
String a = "Bob"; // create object in string pool(perm-gen)
String b = "Bob"; // getting existing object.
你有多注意:
For efficiency, Java makes only one string object for every string constant.
2)
String nickname = name.substring(0,3);
由于String是不可变对象name.substring(0,3);在堆内存中创建了新的String(“Rob”),而不是在perm-gen中.
注意 :
In Java 8 String pool is created in PermGen area of Heap, garbage collection can occur in perm space but depends upon JVM to JVM. By the way from JDK 1.7 update, String pool is moved to heap area where objects are created.
阅读更多here.