==和equals

136 阅读1分钟

1. 基本类型的值 == 基本类型的值

2. 对象地址 == 对象地址

(注意Integer -128 ~ 127 在缓存中有,不用New) (String的串常量都放在常量池里,地址相等)

3. 对象地址 Object.equals 对象地址

4. String和Integer等包装类型重写过equals方法,比较的是对象内容。

(StringBuffer没有重写)

5. 程序实例:

public static void main(String[] args) {
        Integer a = 100;
        Integer b = 100;
        Integer c = 1000;
        Integer d = 1000;
        System.out.println("a.equals(b):"+a.equals(b));
        System.out.println("c.equals(d):"+c.equals(d));
        System.out.println("a == b:" + (a == b));
        System.out.println("c == d:"+ (c == d));
        System.out.println("String sa.equals(sb):"+(sa == sb));
    }
// 结果

a.equals(b):true
c.equals(d):true
a == b:true
c == d:false
String sa.equals(sb):true