JAVA String创建对象问题

2025-05-14 15:04:59
推荐回答(2个)
回答(1):

问题1,创建了四个对象
这个问题一般是很容易混淆的两个概念: String s1="hello"; 与String s2=new String("hello");这两种写法jvm的内存分配时不一样的处理方式。

String s1 ="hello";可能创建一个或者不创建对象,如果"hello"这个字符串在java String池里不存在,会在java String池里创建一个创建一个String对象("hello"),然后s1指向这个内存地址,无论以后用这种方式创建多少个值为"hello"的字符串对象,始终只有一个内存地址被分配,之后的都是String的拷贝,Java中称为“字符串驻留”,所有的字符串常量都会在编译之后自动地驻留。
String s2 = new String("hello");至少创建一个对象,也可能两个。因为用到new关键字,肯定会在heap中创建一个s2的String对象,它的value是“hello”。同时如果这个字符串再java String池里不存在,会在java池里创建这个String对象“hello”。
以下代码运行结果可以证明
public static void main(String[] args) {
String s1= new String("hello");
String s2= new String("hello");
System.out.println(s1==s2);
String s3="hello";
String s4="hello";
System.out.println(s3==s4);

System.out.println(s1==s3);
System.out.println(s1.equals(s3));
}
运行结果是:
false
true
false
true

回答(2):

请用equals;
==比较的是内存地址