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
PRO
William Li
Pro Student 26,807 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.