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 String Equality

Aditya Puri
Aditya Puri
1,080 Points

Why can't I do this same thing using if(noun === "dork") ??

Why can't I do this same thing using if(noun === "dork") ??

Whenever I try to do so, I get an error.

Does "===" only compare 2 numeral values? Is that why it doesn't work?

3 Answers

Alexander Nikiforov
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Alexander Nikiforov
Java Web Development Techdegree Graduate 22,175 Points

Triple equal === is used in JavaScript ( and may be in other Languages I don't know), but not in Java. If as I hope you are running the code in Java, then when comparing strings use equalsTo method, here is post on Stack about different types of comparison:

http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java

Also Craig has a wonderful workshop about comparing Strings. Please take a look if you want to understand more:

https://teamtreehouse.com/library/the-thing-about-strings-2

Aditya Puri
Aditya Puri
1,080 Points

What does he means when he says the '"bar" == "bar" will evaluate to true' BUT '"fooStrings1" == "fooSrings2" wont' in the 2nd best answer?

Is this because 2 equal raw string values (like "abc" and "abc") are considered as the same objects whereas 2 String variables, both of which contain the same string are considered as 2 different objects?

And "==" only compares objects so it will give false?

Dustin Bryce Flanary
Dustin Bryce Flanary
17,663 Points

A comment in another StackOverflow post helps a bit:

"You use operator!= or operator== when you want to check for identity of two objects [if they are actually the same object]

"You use equals() when you want to check for equality. [if two object are equal, as the equals() method defined them].

"It is hard to know what exactly you are trying to achieve, but usually when comparing two reference objects, we want to use equals()." [Ref: http://stackoverflow.com/questions/9537351/how-to-compare-two-objects-references-in-java]

Basically, fooStrings1 & fooStrings2 are different objects [that refer or point to the same variable]. == checks to see if the objects are the same. equals() will check if they have the same value.