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 trial

Java Java Basics Perfecting the Prototype Censoring Words - Using Logical ORs

equals

in the video we use noun.equals, but can I use == as well? What is the difference?

2 Answers

William Li
PLUS
William Li
Courses Plus Student 26,868 Points

In Java, when comparing 2 Strings for equality

  • == test for object equality, namely, whether 2 Strings are the same object. It'd return false in the case when two String are NOT the same objects even if they has the exact same String values.
  • on the other hand, the .equals() methods test only for the String's value equality.

Here's a simple example.

String noun1 = "abc";
String noun2 = new String("abc");  // create a new String object with same value

Now we have 2 different String objects. You can test their equality in the Java REPL using == and .equals().

noun1 == noun2;        // false, because they aren't the same String object.
noun1.equals(noun2);  // true, as they do have the same String value

Does that make sense? Hope the info is helpful to you.