Comparing Objects in Java

I’m taking advantage of training materials offered through an alliance with my school and ElementK to bone up on Java. I am currently taking the Java Fundamentals course which is a nice follow-up to the Intro to Computer & Programming course I just completed. With a little Java under my belt, I know that comparing two Object variables using the == operator can lead to unwanted results. In Java, object variables only hold the address in memory where the object is stored. Backing up a bit, here’s the code for creating an object in Java:

Classname objVar = new Classname();

The new operator allocates memory for the object to be created, calls the Class constructor and returns a reference to that memory which is then assigned to objVar. 

So, if you do a direct comparison of two object variables like this obj1 == obj2, you are really comparing the memory locations of the objects you want! Unless your specific intent is to check and see if an object is an alias of another, you should avoid direct comparisons if you’re really trying to compare the state of two objects. 

Imagine my surprise to find this snippet of code in ElementK’s training files for testing equality: 

Elementk-wrongcomparison

 

In this case, my recommended change would be:

System.out.print(paintDept.getName().equalsIgnoreCase(lumberDept.getName()));

where the getName() method returns a String object which we can them compare using the built-in equals or equalsIgnoreCase methods to compare the values returned by getName().

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s