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.
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.
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.
Videos
In class we were discussing this and basically I understood == tests the EXACT same thing... since Strings are each their own object, we need a special method to check for if they are actually the same words. Furthermore, == tests the address I believe?
Here's the confusing part for me... Java has optimized == so SOMETIMES "hello" == "hello" will return true even if they are two unique Strings... but "hell" += "o" == "hello" returns false. Why ?
You need to do some reading up on the String Constant Pool and the difference between Stack and Heap memory(Strings and their construction are usually discussed in detail here for reasons that will become clear).
Sorry for the short answer but it's a very dense topic that is usually covered across multiple chapters in books. This will get you what you need though.
== operator checks the equality of the object identity, i.e. 2 objects == each other if they are indistinguishable from each other. Currently, in Java, each object has its own unique identity, but not a unique address. As a result, understanding that == tests for address equality is not correct.
Java does not optimised == so that "hello" == "hello", the thing got optimised here is how Java stores the String object, which leads to 2 string literal declarations with the same contents are detected and assigned to a single String object.
I'm currently working on a project that involves comparing strings, but I keep getting stuck on whether to use the "==" operator or the ".equals()" method. From what I've gathered so far, they seem to do the same thing - is it true? Or are there cases where one should be used over the other?
My CS teacher told me that you have to use .equals() when comparing strings instead of == but today I tried using == and it worked. Was this supposed to happen or was it like a new update?
public class Main{
public static void main(String[] args) {
String name = "jarod";
if(name == "jarod"){
System.out.println("ELLO JAROD");
}else{
System.out.print("NO");
}
}
}For this bit of code the output was ello Jarod and if I put in something else for the string variable it gave me no
In general, the answer to your question is "yes", but...
.equals(...)will only compare what it is written to compare, no more, no less.- If a class does not override the equals method, then it defaults to the
equals(Object o)method of the closest parent class that has overridden this method. - If no parent classes have provided an override, then it defaults to the method from the ultimate parent class, Object, and so you're left with the
Object#equals(Object o)method. Per the Object API this is the same as==; that is, it returns true if and only if both variables refer to the same object, if their references are one and the same. Thus you will be testing for object equality and not functional equality. - Always remember to override
hashCodeif you overrideequalsso as not to "break the contract". As per the API, the result returned from thehashCode()method for two objects must be the same if theirequalsmethods show that they are equivalent. The converse is not necessarily true.
With respect to the String class:
The equals() method compares the "value" inside String instances (on the heap) irrespective if the two object references refer to the same String instance or not. If any two object references of type String refer to the same String instance then great! If the two object references refer to two different String instances .. it doesn't make a difference. Its the "value" (that is: the contents of the character array) inside each String instance that is being compared.
On the other hand, the "==" operator compares the value of two object references to see whether they refer to the same String instance. If the value of both object references "refer to" the same String instance then the result of the boolean expression would be "true"..duh. If, on the other hand, the value of both object references "refer to" different String instances (even though both String instances have identical "values", that is, the contents of the character arrays of each String instance are the same) the result of the boolean expression would be "false".
As with any explanation, let it sink in.
I hope this clears things up a bit.
Yes there is a major difference, Case sensitivity.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_string.htm
> equals(stringOrId) Returns true if the passed-in object is not null and represents the same binary sequence of characters as the current string. Use this method to compare a string to an object that represents a string or an ID.
== is same as equalsIgnoreCase(secondString)
Returns true if the secondString is not null and represents the same sequence of characters as the String that called the method, ignoring case.
I would add that == is more null safe. Consider the following examples.
String a;
String b = null;
system.assert(a == b);
This will pass.
String a;
String b = null;
system.assert(a.equals(b));
This will throw a null pointer exception.
The above demonstration is why I tend to prefer == over .equals. If you are going to use .equals, you should always first check that it is not null, though it is not necessary when using constants.
final String SOME_CONSTANT = 'abc';
...
if (SOME_CONSTANT.equals('abc'))
{
// do stuff
}
if (someParameter == SOME_CONSTANT)
{
// do other stuff
}
Also note that while .equals is case sensitive, you can still call .equalsIgnoreCase.
In addition to what I've already stated, I did some informal profiling and it seems == may be significantly faster than .equals. More than 7 times as fast.
.equals
String a = 'abc';
String b = 'abc';
DateTime start = Datetime.now();
for (Integer i = 0; i < 100000; i++) Boolean isEqual = a.equals(b);
Decimal interval = Datetime.now().getTime() - start.getTime();
system.debug(interval); // yields 1831
.equalsIgnoreCase
String a = 'abc';
String b = 'abc';
DateTime start = Datetime.now();
for (Integer i = 0; i < 100000; i++) Boolean isEqual = a.equalsIgnoreCase(b);
Decimal interval = Datetime.now().getTime() - start.getTime();
system.debug(interval); // yields 1514
==
String a = 'abc';
String b = 'abc';
DateTime start = Datetime.now();
for (Integer i = 0; i < 100000; i++) Boolean isEqual = a == b;
Decimal interval = Datetime.now().getTime() - start.getTime();
system.debug(interval); // yields 239
Even the slowest of these is consuming less than 1/5 ms per execution, but if you get in a big loop and your calls start to number in the millions, that can add up.