String s = new String(「hello」)和String s = 「hello」;的區別?spa
String s = new String(「hello」)會建立2(1)個對象,String s = 「hello」建立1(0)個對象。
注:當字符串常量池中有對象hello時括號內成立!code
==與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。如下講解==blog
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。圖片