I don't understand why the operator "==" will not work for comparing string, but will for comparing int, double, float, etc. from what i understand, "==" determines if two entities are pointing to the same object.
The root of your misunderstanding is that the primitive values like 1
and false
and 3.14159
are NOT objects. They are values that DO NOT have an object identity.
In Java there are two kinds of type:
- Primitive data types ... for which
==
compares the values
- Reference types ... for which
==
compares the object identity
a and b are have different reference in memory but this statement returns true.
Now you are confusing something else. a
and b
are actually variables. And yes, behind the scenes variables do have corresponding memory addresses.
However ... a == b
DOES NOT compare the addresses the variables. It compares the content of the variables. And the content of the variables are primitive values that don't have an address.
i thought "==" compares reference?
For reference types (objects and arrays), the ==
operator compares references.
For primitive types, the ==
operator compares the actual values.
Think about it. You want 42
to be equal to 42
... no matter how the numbers were generated.
And just to get back to String
. Despite being "built in" to the Java language, the String
type is a reference type (the class java.lang.String
) and ==
compares it using reference type semantics; i.e. by comparing identity. This is a cause of considerable confusion for new Java programmers (hence the knee-jerk closure), but it is a perfectly logical if you understand the bigger picture.
Now, things do get more complex when we throw the wrapper types and boxing / unboxing into the mix. But that is beyond the scope of your question.