String.equals versus ==
It's good to notice that in some cases use of "==" operator can lead to the expected result, because the way how java handles strings - string literals are interned (see String.intern()
) during compilation - so when you write for example "hello world"
in two classes and compare those strings with "==" you could get result: true, which is expected according to specification; when you compare same strings (if they have same value) when the first one is string literal (ie. defined through "i am string literal"
) and second is constructed during runtime ie. with "new" keyword like new String("i am string literal")
, the ==
(equality) operator returns false, because both of them are different instances of the String
class.
Only right way is using .equals()
-> datos[0].equals(usuario)
. ==
says only if two objects are the same instance of object (ie. have same memory address)
Update: 01.04.2013 I updated this post due comments below which are somehow right. Originally I declared that interning (String.intern) is side effect of JVM optimization. Although it certainly save memory resources (which was what i meant by "optimization") it is mainly feature of language
Meet Jorman
Jorman is a successful businessman and has 2 houses.
But others don't know that.
Is it the same Jorman?
When you ask neighbours from either Madison or Burke streets, this is the only thing they can say:
Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons.
That's how the operator ==
behaves. So it will say that datos[0]==usuario
is false, because it only compares the addresses.
An Investigator to the Rescue
What if we sent an investigator? We know that it's the same Jorman, but we need to prove it. Our detective will look closely at all physical aspects. With thorough inquiry, the agent will be able to conclude whether it's the same person or not. Let's see it happen in Java terms.
Here's the source code of String's equals()
method:
It compares the Strings character by character, in order to come to a conclusion that they are indeed equal.
That's how the String equals
method behaves. So datos[0].equals(usuario)
will return true, because it performs a logical comparison.
Use the string.equals(Object other)
function to compare strings, not the ==
operator.
The function checks the actual contents of the string, the ==
operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==
, but it's better not to rely on that.
if (usuario.equals(datos[0])) {
...
}
NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos
array otherwise you'll get an array-out-of-bounds exception.