Identity and equality in programming refers to the aspect of checking whether objects/variables are the ‘same’ by value or reference
Identity
Two variables/objects have the same identity if they both have the same reference i.e. they both point to the same memory address. Most languages use double equals (==
) to check for identity.
Most Programming Languages define primitive data types with in-built identity checking, which we usually take for granted:
int x = 20;
int y = 20;
int z = x
print(x == y) //Returns 1 (True)
print(x == z) //Returns 1 (True)
print(z == 20) //Returns 1
This functionality extends to complex data types as well:
int A1[10];
int* A3 = A1; //C doesn't support full array copying, but we have two pointers to the same address now.
print(A1 == A3) //Returns 1 (True)
or in Java:
Circle C1 = new Circle();
Circle C2 = C1;
Circle C3 = new Circle();
System.out.println(C1 == C2); //Returns true
System.out.println(C1 == C3); //Returns false, as C1 & C3 are stored in different memory locations
However, in most cases it isn’t as useful, as we are interested in whether two complex data types have the same data (or value), not reference. In other words, we’re interested in equality.
Equality
Two variables/objects are equal if they have the same value. In primitive data types, the identity-checking operator and the equality operator are the same (==
) and do the same thing. For example, two different int variables would obviously have the same value if they point to the same memory address (where whatever that number is is stored). The same thing applies to other primitives like characters.
Floating Point Equality - Just... Don't
Generally Floats suffer from some loss in precision, because#todo .
However, we can’t really do that for complex data types, as we need to implement our own equality checking function.
For example, C’s qsort
function requires a cmp
(comparison) function to be passed to it so it can properly check when two complex data types are equal, lesser or greater compared to each other.
In Java, the standard method equals()
is used for equality checking.