String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String s4 = "hello" + "world";
String s5 = s1+"world";
String s6 = "hello"+s2;
String s7 = s1 + s2;
System.out.println(s3 == s4); //true
System.out.println(s3 == s5); //false
System.out.println(s3 == s6); //false
System.out.println(s5 == s6); //false
注意事项1:
在Java中,如果有两个String类型的变量进行比较,a==b是对两个变量的地址值进行比较,而a.equal(b)是对两个变量的值进行比较
注意实现2:
常量与常量的拼接结果保存在常量池内,且常量池中不会存在相同的常量,如s3==s4。
而常量与变量的拼接结果会保存在堆内,且生成的地址不同,如s5==s6。