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.

Answer from Alnitak on Stack Overflow
Top answer
1 of 16
611

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.

2 of 16
593

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.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ java โ€บ difference-between-and-equals-method-in-java
Difference Between == Operator and equals() Method in Java - GeeksforGeeks
January 4, 2025 - The main difference is that string equals() method compares the content equality of two strings while the == operator compares the reference or memory location of objects in a heap, whether they point to the same ...
๐ŸŒ
W3Schools
w3schools.com โ€บ java โ€บ ref_string_equals.asp
Java String equals() Method
Java Examples Java Videos Java ... to find out if they are equal: String myStr1 = "Hello"; String myStr2 = "Hello"; String myStr3 = "Another String"; System.out.println(myStr1.equals(myStr2)); // Returns true because they are ...
๐ŸŒ
Scaler
scaler.com โ€บ home โ€บ topics โ€บ difference between comparing string using == and .equals() method in java
Difference between Comparing String Using == and .equals() Method in Java - Scaler Topics
June 2, 2024 - If obj1 is equal to obj2, the equals() method returns true; otherwise, it returns false. ... Since we are comparing the strings char by char using the equals() method, it is an O(n) operation where n is the size of the shortest string.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ why to never use == with strings and instead use .equals()
r/learnjava on Reddit: Why to never use == with Strings and instead use .equals()
August 9, 2020 -

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 ?

๐ŸŒ
Medium
medium.com โ€บ @oguzkaganbati โ€บ why-should-we-use-equals-method-instead-operator-for-string-comparison-in-java-510fc50057cc
Why Should We Use โ€œequals()โ€ Method Instead โ€œ==โ€ Operator for String Comparison in Java? | by OฤŸuz KaฤŸan BATI | Medium
March 5, 2024 - By using the equals() method, weโ€™re comparing the content of โ€˜str1โ€™ and โ€˜str2โ€™, which in this case is โ€˜helloโ€™. Therefore, the output is true, indicating that the strings have the same content. In Java, when comparing strings, itโ€™s crucial to use the equals() method instead of the โ€˜==โ€™ operator.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ can i use == in java for strings
r/learnjava on Reddit: Can I use == in Java for strings
October 8, 2024 -

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

Find elsewhere
๐ŸŒ
Team Treehouse
teamtreehouse.com โ€บ community โ€บ java-string-equals-string-in-if-statement
Java string equals string in if statement (Example) | Treehouse Community
April 2, 2019 - The goal is to print "first is equal to second" if firstExample is the same thing as secondExample. String firstExample = "hello"; String secondExample = "hello"; String thirdExample = "HELLO"; // this is what the lesson uses and probably is wanting us to use for this, and fails the check, without printing anything into the "output" tab if (firstExample.equals(secondExample)) { console.printf("first is equal to second"); System.exit(0); } // also does not work, === or == if (firstExample == secondExample) { }
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ difference-between-equals-java-babar-shahzad
Difference Between == and equals() in Java
March 29, 2023 - We use equals to compare s1 and ... between "==" and "equals" in Java is that "==" compares the memory location of two objects, while "equals" compares the contents of two objects....
๐ŸŒ
How to do in Java
howtodoinjava.com โ€บ home โ€บ string โ€บ java string.equals()
Java String.equals() with Examples - HowToDoInJava
January 9, 2023 - As mentioned earlier, '==' operator checks for the same object references. It does not check for string content. Whereas equals() method strictly checks for string content only. In the following Java program, we have created two String objects.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnjava โ€บ help me understand the difference between "==" and ".equals()" in java
r/learnjava on Reddit: Help me understand the difference between "==" and ".equals()" in Java
July 15, 2025 -

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?

Top answer
1 of 5
49
From what I've gathered so far, they seem to do the same thing - is it true? No. They don't do the same thing. .equals() is a method, so it only applies to objects (reference types). The method compares the content of an object to another. == is an operator - a test for equality on primitive types and for identity (being the same) for objects (reference types). Generally, you should always use .equals with objects - including String values (they also are objects). The exception is if you want to test if two objects (actually their object references) are identical (have the same reference).
2 of 5
38
The difference is a bit hard to explain using strings, so let's use cars instead! Imagine you and your neighbor both own the same car - two different objects but same manufacturer, same color, same number of seats and so on. .equals() will be true because both these cars share the same properties.  However, == will be false because it's two different cars parking in two different parking lots. Let's say you have a daughter and she's learning to drive. For this reason, you allow her to use your car. You set herCar = yourCar. This means herCar == yourCar because both terms/variables ("herCar" and "yourCar") POINT to the exact same car. If you ask someone to point his finger to her car, he'll point at exactly the same car as when you ask him to point at yours. Another example: if someone hits your car with a stone, causing a bruise, this bruise will also exist on your daughter's car because it is the exact same vehicle. However there won't be a bruise on your neighbor's car because yours and his only equal, but they don't ==. Let's go back to strings: .equals() checks whether the strings look the same, have the same length and consist of the same characters in the same order. == checks whether two strings are stored on the same position inside your computer memory. So if you have a string "ExampleString" stored in your memory several times on several positions, == will only be true if you compare variables pointing to the exact same position of the exact string in your computer memory. It will be false otherwise, even if the strings are the same text. This is the case for all objects. For this reason, you should always use equals for objects. --- tl;dr: .equals() means "does it look the same" and can return true even if it's two different objects in your computer memory. == means "is it EXACTLY the same" and can return false even if the objects are 100% equal as long as it's two different objects stored in different positions in your computer memory.
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ java โ€บ java string equals vs
Comparison Between string.equals() vs == in Java | Delft Stack
March 11, 2025 - Regardless of how the strings are created, as long as the content is the same, string.equals() will confirm their equality. On the other hand, the == operator compares the memory addresses of the string objects.
๐ŸŒ
Java67
java67.com โ€บ 2012 โ€บ 11 โ€บ difference-between-operator-and-equals-method-in.html
Difference between == and equals() method in Java? String Example | Java67
Btw, if you are not familiar with essential OOP concepts like overloading and overriding then you should first check these Java online courses o understand. That will help you to understand the difference between the equals() method in the Object class and the String class. For example java.lang.String class overrides the equals() and hashcode method and in the overridden method, it will check that two string contains same value or character if yes then they are equals otherwise not equal.
๐ŸŒ
Programiz
programiz.com โ€บ java-programming โ€บ examples โ€บ differentiate-string-equals
Java Program to Differentiate String == operator and equals() method
equals() checks if the content of the string object are equal. Here, the content of both the objects name1 and name2 is the same Programiz. Hence, it returns true. class Main { public static void main(String[] args) { String name1 = new String("Programiz"); String name2 = name1; System.out...
๐ŸŒ
GitHub
gist.github.com โ€บ Yengas โ€บ 9040261
Java String comparison, differences between ==, equals, matches, compareTo ยท GitHub
String x = "hello+"; String y = "hello+"; System.out.println(x.matches(y)); // => false System.out.println(x.equals(y)); // => true ยท Now we see the difference between these methods easily. ... I have done some tests in String Pool. There was a unclear case related to your code examples.
๐ŸŒ
Baeldung
baeldung.com โ€บ home โ€บ java โ€บ java string โ€บ comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - Using the โ€œ==โ€ operator for comparing text values is one of the most common mistakes Java beginners make. This is incorrect because โ€œ==โ€ only checks the referential equality of two Strings, meaning if they reference the same object or not. Letโ€™s see an example of this behavior: String string1 = "using comparison operator"; String string2 = "using comparison operator"; String string3 = new String("using comparison operator"); assertThat(string1 == string2).isTrue(); assertThat(string1 == string3).isFalse(); In the example above, the first assertion is true because the two variables point to the same String literal.
๐ŸŒ
Medium
medium.com โ€บ @AlexanderObregon โ€บ understanding-the-difference-between-equals-and-in-java-10a075326720
Understanding the Difference Between equals() and == in Java
April 24, 2024 - String str1 = new String("Hello"); ... str3); // Output: true ยท In the example above, str1 and str2 are different objects with the same content, so str1 == str2 returns false....
Top answer
1 of 16
762

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 hashCode if you override equals so as not to "break the contract". As per the API, the result returned from the hashCode() method for two objects must be the same if their equals methods show that they are equivalent. The converse is not necessarily true.
2 of 16
140

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.

๐ŸŒ
Medium
medium.com โ€บ @alxkm โ€บ java-string-comparison-a-complete-guide-44df959a756f
Java String Comparison โ€” A Complete Guide | by Alex Klimenko | Medium
July 11, 2025 - It returns true if both objects ... differ. For example, Objects.equals(str1, str2) will correctly return true even if both strings are null, and it won't throw a NullPointerException....