[JAVA] Detailed explanation of the difference between equals and "==" in Java; get memory address

Recommended good article: Detailed explanation of the difference between equals and "==" in Java

View memory address function

import org.openjdk.jol.vm.VM;

VM.current().addressOf()

Example:

import org.openjdk.jol.vm.VM;

public class passbyValue_Reference {
    
    
    public static void main(String[] args) {
    
    
        Integer a = 100;
        Integer b = 100;

        Integer c = 128;
        Integer d = 128;

        Integer x = 127;
        Integer y = 127;

        System.out.println("a = 100 address: " + VM.current().addressOf(a));
        System.out.println("b = 100 address: " + VM.current().addressOf(b));

        System.out.println("c = 128 address: " + VM.current().addressOf(c));
        System.out.println("d = 128 address: " + VM.current().addressOf(d));

        System.out.println(a == c); // false
        System.out.println(b == d); // false

        System.out.println(a == b); // true
        System.out.println(a.equals(b)); // true

        System.out.println(c == d); // false
        System.out.println(c.equals(d)); // true

        System.out.println(x == y); // true
        System.out.println(x.equals(y)); // true

        /*
        // 定义一个Integer变量时,会默认进行Integer.valueOf(a)操作
        public static Integer valueOf(int i) {
            assert IntegerCache.high >= 127;
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
        */
    }
}

output

a = 100 address: 31911821712
b = 100 address: 31911821712
c = 128 address: 31913988872
d = 128 address: 31913988888
false
false
true
true
false
true
true
true

Guess you like

Origin blog.csdn.net/xiaoyue_/article/details/129850653