== 和 equals()的区别?
A: ==
基本类型:比较的是基本类型的值是否相同
引用类型:比较的是引用类型的地址值是否相同
B:equals()
只能比较引用类型,默认比较的是对象的地址值是否相同。
但是,可能被重写,一定要根据实际的情况来看,例如String类的equals()比较字符串内容是否相等。
/*
* String s = new String(“hello”)和String s = “hello”;的区别
*
* ==:比较引用类型,比较的是地址值
* equal():默认比较的是地址值。String类重写了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
}
}
public class StringDemo3 {
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
}
}
/*
* 看程序写结果
* 字符串变量相加:先开空间,再加内容
* 字符串常量相加:先加,再找,没有再开空间
*/
public class StringDemo4 {
public static void main(String[] args) {
String s1 = "hello";
String s2 = "world";
String s3 = "helloworld";
String s4 = s1 + s2;
String s5 = "hello"+"world";
System.out.println(s4);
System.out.println(s5);
// System.out.println(s3 == s1 + s2);// false
// System.out.println(s3.equals(s1 + s2));// true
// System.out.println(s3 == "hello" + "world");// true
}
}