String s = new String(“hello”)和String s = “hello”;的区别?
String s = new String(“hello”)会创建2(1)个对象,String s = “hello”创建1(0)个对象。
注:当字符串常量池中有对象hello时括号内成立!
==与equals()的区别:
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
}
}
**运行结果:**
> false
> true
public class StringDemo1 {
public static void main(String[] args) {
String s1 = new String("hello");
String s2 = new String("hello");
System.out.println(s1 == s2);// false
System.out.println(s1.equals(s2));// true
String s3 = new String("hello");
String s4 = "hello";
System.out.println(s3 == s4);// false
System.out.println(s3.equals(s4));// true
String s5 = "hello";
String s6 = "hello";
System.out.println(s5 == s6);// true
System.out.println(s5.equals(s6));// true
}
}
s1~s6用equals()的比较不解释,都是比较的值,均为true。以下讲解==
public class StringDemo4 {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
System.out.println(s3 == s1 + s2);// false
System.out.println(s3.equals((s1 + s2)));// true
System.out.println(s3 == "hello" + "world");//false
System.out.println(s3.equals("hello" + "world"));// true
}
}
equals()比较方法不解释,比较值,均相等,均为true。
Java String a=new String("ABC")的创建
原文:https://www.cnblogs.com/taochen-go/p/9475947.html