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: 



In this case, my recommended change would be:


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


Code Academy!

I finally got around to finishing some lessons in Having a little bit of programming experience (very little Python, a little Java experience) helped me complete the exercises faster. After completing the exercises, I’m hungry for more. I took advantage of some O’Reilly specials to purchase some eBooks about JavaScript specifically:

  1. JavaScript: The Good Parts
  2. JavaScript & jQuery: The Missing Manual 2nd Edition

I haven’t actually read them yet but with my upcoming free time, I’ll make some headway. So much to do! 🙂 Without making this post longer than it needs to be, here are the achievements I unlocked!


but there’s not “follow-up”