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。图片