String a="hello";和String a=new String的区别

2025-03-10 11:19:16
推荐回答(2个)
回答1:

语句String a="hello"; 是声明一个的变量,变量类型是String,值是hello,
语句String a = new String("hello");是声明一个对象,对象类型是Strinig,内容是hello。

回答2:

String s = new String(“hello”)和String s = “hello”;
前者会创建2个对象,后者创建1个对象。
public class StringDemo2 {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = "hello";

System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
}
}