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 if() {}

I'm doing the Java Basics course and I am wondering why the following doesn't work?

if(noun == "dork") {}

This is the way it apparently must be done.

if(noun.equals("dork")) {}

Jeff

4 Answers

== will compare if noun and "dork" are the same object.

where as .equals will compare the equality of the value of noun and the value of "dork"

== is "are they the same dork" .equals is "are they both dorks"

Note: this is different when dealing with custom objects/inheritance etc.)

Rui Bi
Rui Bi
29,853 Points

Unlike languages like PHP, Ruby, Python, and JavaScript, Java makes strict distinctions between the various times. In Java, int, boolean, float, double, and char are, "primitive" types, and can be compared directly using ==. You can only directly compare primitive types using ==.

However, Strings are objects in Java, and are not a primitive type. That is also the reason why String is the only capitalized type, while the others are all lowercase.

When used with objects, == in Java is actually checking to see if the two references refer to the same object. For instance, if you had:

String s ="hi"; String a = s;

Then a == s would return true.

Most Java objects provide a method for comparison, the .equals() method. In the case of strings, .equals() will return true if the two strings contain the same data, even if they are separate objects. Later on, if you get into more Java programming, you will create your own objects and get a chance to provide custom ways for specifying how you want instances of your object to be compared.

The good thing about Java's way of doing things using, "strict typing," is that you never have to worry about things like === and !==, since only things of the same type can be compared (However, you will find that you can do certain things like compare chars and integers, for example, 'a' == 97 would return as true).

Craig Dennis
STAFF
Craig Dennis
Treehouse Teacher

Hi Jeff,

Great question and one that is often asked.

Here is a pretty detailed Stack Overflow answer.

Let me know if that helped clear up your question, or if you'd like me to break that down a little more.

Hope it helps!

Thanks Cody and Craig. After running through my head enough times it will sink in.