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: