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...