String.equals versus == [duplicate]
Solution 1:
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.
Solution 2:
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.