"hello"这种方式创建字符串时,
-- jvm会检查字符串常量池中是否具备"hello"的字符串对象,
-- 如果不具备则在字符串常量池中创建该字符串对象
-- 如果该对象已经存在在内存中了,则直接返回该字符串的内存地址即可
new String("hello")这种方式创建字符串对象
-- jvm首先会检查字符串常量池中是否具备该字符串对象
-- 如果已经存在则不会再创建了
-- 如果不存在则在字符串常量池中创建该字符串的对象
-- 然后再去堆内存中创建字符串对象,返回堆内存中的字符串的内存地址
equals 默认情况下比较的是内存地址,String类重写了object的equals方法,比较的是字符串的内容是否一致
public class Demo1 {
public static void main(String args[]){
String str1 = "hello";
String str2 = "hello";
String str3 = new String("hello");
String str4 = new String("hello");
System.out.println("str1==str2?"+(str1==str2)); //true
System.out.println("str2==str3?"+(str2==str3)); // false
System.out.println("str3==str4?"+(str3==str4)); // false
System.out.println("str2.equals(str3)?"+(str2.equals(str3))); // true
System.out.println("str3.equals(str4)?"+(str3.equals(str4))); // true
}
}
输出内容
str1==str2?true
str2==str3?false
str3==str4?false
str2.equals(str3)?true
str3.equals(str4)?true
网友评论