string字符串的创建可以通过String str1="hello"或者 String str2 = new String("hello")两种形式。
使用String str1="hello"这种方式创建字符串的时候,jvm首先会检查字符串常量池中是否存在该字符串的对象,如果已经存在,那么就不会在字符串常量池中再创建了,直接返回该字符串在字符串常量池中的内存地址。如果该字符串还不存在字符串常量池中,那么就会在字符串常量池中先创建该字符串的对象,然后再返回。
new String("hello")这种方式创建字符串对象的时候,jvm首先会检查字符串常量池中是否存在该“hello”字符串的对象,如果已经存在,那么就不会在字符串常量池中再创建了,如果该字符串还不存在字符串常量池中,那么就会在字符串常量池中先创建该“hello”字符串的对象,然后还会到堆内存中再创建一份字符串的对象,把字符串常量池中“hello”字符串内容拷贝至堆内存中的字符串对象,然后返回堆内存中字符串的内存地址。
String str1="hello";
String str2="hello";
String str3=new String(“hello”);
String str4=new String(“hello”);
System.out.println(str1==str2); true
System.out.println(str2==str3); false
System.out.println(str3==str4); false
System.out.println(str3.equals(str4)); true 这里equals比较的是字符串的内容