equals和==的区别
示例1:
public static void main(String[] args) { String s1 = "test"; String s2 = "test"; if (s1 == s2) System.out.println("s1 == s2"); else System.out.println("s1 != s2"); }
结果:
s1 == s2
示例2:
public static void main(String[] args) { String s1 = "test"; String s2 = new String("test"); if (s1 == s2) System.out.println("s1 == s2"); else System.out.println("s1 != s2"); if(s1.equals(s2)) System.out.println("s1 equals s2"); else System.out.println("s1 is not equal to s2"); }
结果:
s1 != s2
s1 equals s2
示例3:
public static void main(String[] args) { String s1 = "test"; String s2 = new String("test"); s2 = s2.intern(); if (s1 == s2) System.out.println("s1 == s2"); else System.out.println("s1 != s2"); if(s1.equals(s2)) System.out.println("s1 equals s2"); else System.out.println("s1 is not equal to s2"); }
结果:
s1 == s2
s1 equals s2
结论:
- 当使用 == 进行比较的时候,比较的是他们在内存中的存放地址。基本数据类型(byte,short,char,int,long,float,double,boolean)之间的比较应该用 ==。
- JAVA当中所有的类都是继承于Object这个基类的。Object中定义了一个equals方法,这个方法的初始行为是比较对象的内存地址(==),但在一些类库当中这个方法被覆盖掉了(如String,Integer,Date),用于比较值。