java 中equals() 与 "=="有什么区别,简单说明
equals方法是java.lang.Object类的方法
有两种用法说明:
一、对于字符串变量来说,使用“==”和“equals()”方法比较字符串时,其比较方法不同。
1、“==”比较两个变量本身的值,即两个对象在内存中的首地址。
(java中,对象的首地址是它在内存中存放的起始地址,它后面的地址是用来存放它所包含的各个属性的地址,所以内存中会用多个内存块来存放对象的各个参数,而通过这个首地址就可以找到该对象,进而可以找到该对象的各个属性)
2、“equals()”比较字符串中所包含的内容是否相同。
例子一:
public class Main {
public static void main(String[] args) {
String s1="hello";
String s2="HELLO".toLowerCase();
System.out.println(s1);
System.out.println(s2);
if (s1.equals(s2)){
System.out.println("s1 equals s2");
}else{
System.out.println("sq Not equals s2!");
}
// write your code here
}
}
执行结果:
hello
hello
s1 equals s2
Process finished with exit code 0
s2 String类型 转换后变量内容与 s1 同为 hello (“equals()”比较字符串中所包含的内容是否相同)
例子二:
public class Main {
public static void main(String[] args) {
String s1="hello";
String s2="HELLO".toLowerCase();
System.out.println(s1);
System.out.println(s2);
if (s1==s2){
System.out.println("s1 == s2");
}else{
System.out.println("sq ==! s2!");
}
// write your code here
}
}
执行结果:
hello
hello
sq ==! s2! (hello 和 HELLO 指向的内存地址不是同一个地址)