Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialA X
12,842 PointsDot notation to Check for Equality vs. Double Equals ( == )
Craig seems to switch suddenly to checking for equality using dot notation in the Welcome Back Objects video vs. the double equals (==). Why the sudden change? Is there an advantage to using one over the other to compare equality? Or are they both just a different way to accomplish the same task? Thanks!
3 Answers
Seth Kroger
56,413 Points== works for comparing the values of primitive variables because they are essentially numbers. Object variables on the other hand are what's called "reference variables", it a reference to a point in memory where the object was created by the new
keyword. This distinction is usually handled transparently, but not here. == doesn't work for comparing the values of objects because the basic numeric value isn't based on what the content of the object is, but on what the location where the object is at in memory. Two objects with the same internal values wouldn't be considered equal by == because they reside in two different locations. This is why using (and defining in you own classes) .equals() is important with objects.
Philip Gales
15,193 PointsString is a type of object, hence why it is uppercase. Because String is an object, you use the method .equals to check for equality.
You are now learning about this in the objects course since it would have been too much in the java basics course.
int is not a method and is a primitive data type, so == is still valid to use.
Craig Dennis
Treehouse TeacherHi nekilof ,
Strings need to be checked with the equals
or equalsIgnoreCase
method. I made a workshop on this that explains why, if you want to dig deeper: The Thing About Strings
Hope that helps!
gyorgyandorka
13,811 Pointsgyorgyandorka
13,811 PointsExcellent answer, thank you!