Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Java The Thing About Strings

Confused with why these does not equal to each other

String firstString = "Dervin"; String differentString = new String("Dervin"); explore("String objects that contain the same characters but point to different objects cannot use double equals", firstString != differentString);

1 Answer

Robert Stefanic
Robert Stefanic
35,157 Points

It's because == checks whether or not the object references are the same. When comparing strings in Java, you need to use .equals(str) on a string in order to check to see if each of the characters in both of the strings are the same.

If you don't use .equals, you are comparing the hash strings of the objects. Each string has different hashcodes, weather of not they contain the same thing.