Sameness in Java: Identity & Equality

In Java, sameness of objects is described with two different concepts: Identity and Equality.

Identity (known as reference equality)
Identity of an instance is correlated with the memory location of the object. Sameness in terms of identity means that; if two references points at the same memory location then that means there is one object that is referenced by different references.

Identity of objects are checked with the equality(==) operator.

String s1 = "Hello";
String s2 = new String("Hello");  
assertFalse(s1 == s2);

However, two distinct references formed of the same string literal point to the same memory location since their references firstly looked up at String pool. Therefore when two String variables formed of same string literal are compared, the result will return true. 

String s1 = "Hello";
String s2 = "Hello";  
assertTrue(s1 == s2);

And here is some examples about the reference equality:

//Null references of same types are equal
String str1 = null;
String str2 = null;
assertTrue(str1 == str2);

Long l = 12L;
Integer i = 12;
assertTrue(l == 12);
assertTrue(i == 12L);
//assertTrue(i == l); //compile error

The numerics' reference equality is done using object cache for the numbers less than 128:

Short I_127 = 127;
Short I_127_2 = 127;
assertTrue(I_127 == I_127_2);
  
Short I_128 = 128;
Short I_128_2 = 128;
assertFalse(I_128 == I_128_2);

Instance Equality (known as equality by value)
Instance equality is determined by the implementation of the equals() method. The equals() method is already implemented in Object class and so every class already have as default implementation. 

The default implementation of the equals() method performs the equality check via reference equality as which we examine above in this article. If a more specialized implementation is required, then the equals method is overriden as usually happened in production scenerios.

String s1 = "Hello";
String s2 = new String("Hello");  
assertTrue(s1.equals(s2));

Yorumlar

Popular

Java 14 New Features

Pretenders, Contenders and Liars

Java 12 New Features