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

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!

Cody Coats
Cody Coats
7,469 Points

== 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.)

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

Rui Bi
Rui Bi
29,852 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).