Equality Operators

Primitive type compare using == , while object compare using equals method.

When compare object with ==, we’re compare the reference (memory location)

Integer

Integer and Long type wrapper will always cache values in the range -128 to 127. If you initialize value between this value it will cache it and return the same hash from pool.

Integer a = 127;  
Integer b = 127;  
System.out.println(a == b); // true
		
Integer s = 128;  
Integer t = 128;  
System.out.println(s == t); // false

Integer x = -128; 
Integer y = -128; 
System.out.println(x == y); // true
		
Integer e = -129; 
Integer f = -129; 
System.out.println(e == f); // false

Autoboxing

Integer a = 127;
Integer b = 127;

a = Integer.valueOf(100);   // autoboxing 
b = 100;                    // autoboxing   
System.out.println(a == b); // true

a = Integer.valueOf(200);   // autoboxing 
b = 200;                    // autoboxing  
System.out.println(a == b); // false

Integer class static method check the boxing value in range -128 to 127, if the value is out of rance, it return a new Integer object value, thus it has different memory or hashcode.

@HotSpotIntrinsicCandidate
public static Integer valueOf(int i) {
  if (i >= IntegerCache.low && i <= IntegerCache.high)
     return IntegerCache.cache[i + (-IntegerCache.low)];
  return new Integer(i);
}

Wrapper Type

Declare and initialize value in wrapper type will return different value.

Long m = new Long(100);
Long n = new Long(100);

System.out.println(m == n); // false

System.out.println("hashcode (m): " + System.identityHashCode(m)); // hashcode (m): 1705929636
System.out.println("hashcode (n): " + System.identityHashCode(n)); // hashcode (n): 1221555852

To compare the Primitive Wrapper / Object’s value, we use equals()

Long m = new Long(100);
Long n = new Long(100);

System.out.println(m.equals(n)); // true

System.out.println("hashcode (m): " + System.identityHashCode(m)); // hashcode (m): 1705929636
System.out.println("hashcode (n): " + System.identityHashCode(n)); // hashcode (n): 1221555852

Internally, the equals method will check on both object are same type, the compare the both value.

public boolean equals(Object obj) {
  if (obj instanceof Long) {
      return value == ((Long)obj).longValue();
  }
  return false;
}

Compare Long and Integer value

Long m = new Long(100);
Integer n = new Integer(100);

System.out.println(m.equals(n)); // false

System.out.println("hashcode (m): " + System.identityHashCode(m)); // hashcode (m): 1705929636
System.out.println("hashcode (n): " + System.identityHashCode(n)); // hashcode (n): 1221555852
Equality Operators

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.