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 trialAlejandro Salas
2,365 PointsJava: Difference between comparing == and equals
What is the difference between checking if two String variables match using == and with the equals method.
2 Answers
Mauro Teixeira
3,727 PointsTo complement, the String.equals() method will actually look "inside" the objects for their value and compare the value of both objects, not the memory position like == does.
equals() is a method inherited from Object, so if you decide to create your own class, you can Override the default equals() so that you can define a behavior on how two objects of your class can be compared. For example, if you define a class Book with properties "name" and "author", you may want to override the equals() method to compare the name and author of both objects being compared.
Andrew Hinton
20,620 PointsThe '==' operator will compare the memory locations of two different strings, not the strings themselves. '==' should only be used for primitive types like ints, chars, etc. If it's an object like a string you'll want to use .equals().