==号比较引用类型比较的是地址值是否相同
equals:比较引用类型默认也是比较地址值是否相同,而String类重写了equals()方法,比较的是内容是否相同。
package name;
public class Text02 {
public static void main(String[] args) {
String s1="hello";
String s2="word";
String s3="helloword";
System.out.println(s3==s1+s2);
System.out.println(s3.equals(s1+s2));
System.out.println(s3=="hello"+"word");
System.out.println(s3.equals("hello"+"word"));
}
}
运行结果为
false
true
true
true
字符串如果是变量相加,先开空间,再拼接,System.out.println(s3= =s1+s2);中s1s2是变量,开空间再比较地址值自然不同。
字符串如果是常量相加,是先加,然后在常量池找,如果有就直接返回,否则,就创建。System.out.println(s3==“hello”+“word”);helloword是常量。