Skip to main content

Equality of Java Objects

There are 3 candidates for the equality test in Java:
1. Primitives
2. References
3. Objects


When we compare things in Java, what is really being compared? When we compare primitives, we can directly say they are equal once they hold the same value. Therefore they can be compared using the == operator. The same is true for reference variables, however, we are not comparing the actual values being referred to, rather we compare the pointers to the actual values.


Primitive



int someInt = 1;
if (someInt == 1) {
//this block will execute
}

The equality of two objects is tested using the equals method of the Object class. The default behavior of the equals method is just the same as the == operator. However, some classes override this method for a specific comparison. One example is the String class, the equals method is overridden to test the equality of the actual strings being held by two String objects.


Object without an overridden equals method



Object a = new Object();
Object b = new Object();

if (a.equals(b)) {
//this block will not execute
}

Object with an overridden equals method



String a = new String("I am a string!");
String b = new String("I am a string!");

if (a.equals(b)) {
//this block will execute depending on the implementation
//of the equals method, for this instance, it compares the string literals
//being held by two String objects
}

So if you are unsure of how the equals method behave in a specific class, RTF API documentation!

Comments

Popular posts from this blog

Architecture Complexity

Here are the items to consider: Coding to an interface Service Oriented Architecture Automated Testing Domain Driven Design Custom Data Access Layer Layered architecture Complexity is relatively equal the number of lines of code. Note that complexity is not bad. It must be justified.

Repair Windows 7 System Files

8 out of 10 average PC users have their box’s system files altered by malwares, viruses, etc. We usually reinstall the OS if the antivirus and anti malware software did not perform their job well. Here’s one way to fix the corrupted system files without the need of restarting your Windows 7 box. 1. Run the Command Prompt as Administrator 2. Type the following command C:\Windows\system32\> sfc /scannow 3. After the verification phase, you will receive a message about your system files’ integrity Windows Resource Protection did not find any integrity violations.