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("str3.equals(str4)" + (str3.equals(str4))); //true
//String类重写了Object的equals方法,比较的时两个字符串对象的内容
//"=="用于比较引用数据类型数据的时候比较的时两个对象的内存地址,equals方法默认情况下比较也是两个对象的内存地址
}
}
String str="hello"方式创建字符串时,jvm会先检查字符串常量池是否存在该字符串的对象,如果已经存在,那么就不会在字符串常量池中创建了,直接返回该字符串在字符串常量池中内存地址,如果该字符串还不存在在字符串常量池中,那么就会在字符串常量池中首先创建该字符串的对象,然乎再将地址返回到栈内存中
new String(“hello”)这种方式创建字符串时,jvm先会检查字符串常量池中是否存在"hello"的字符串,如果已经存在,则不会在字符串常量池中创建了,如果还没有存在,那么就会在字符串常量池中创建"hello"字符串,然后还会到堆内存中再创建一份字符串的对象,把字符串常量池中的"hello"字符串内容拷贝到堆内存中的字符串对象,然后返回堆内存中字符串对象的内存地址。

本文通过一个Java示例程序详细解释了字符串对象的创建过程,包括使用字符串常量池和new关键字创建的不同方式,并对比了==与equals方法的区别。
983

被折叠的 条评论
为什么被折叠?



