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
🌐
Medium
medium.com › @deepshah201 › java-vs-equals-e3d0f9c0a7fb
vs .equals(). String comparison in Java can lead to…
October 7, 2024 - Using .equals(): This method returns true because both s1 and s2 contain the same characters. Using ==: This also returns true because both s1 and s2 reference the same string object in the string pool. Java optimizes memory usage by reusing string literals.
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.

Discussions

Can I use == in Java for strings
For objects if you do object1 == object2 then it's comparing the memory addresses of those objects which is essentially asking "are these the same object?" rather than "are these equal?". If you use .equals() it will invoke the .equals implementation of the class. Default implementation of .equals? You guessed it, it compares the memory addresses. Like the automod says, Strings in java do a lot of unreliable stuff with == being one of the things. More on reddit.com
🌐 r/learnjava
43
23
October 8, 2024
programming languages - Why didn't == operator string value comparison make it to Java? - Software Engineering Stack Exchange
Every competent Java programmer knows that you need to use String.equals() to compare a string, rather than == because == checks for reference equality. When I'm dealing with strings, most of the ... More on softwareengineering.stackexchange.com
🌐 softwareengineering.stackexchange.com
April 2, 2013
Java string equals string in if statement
Lee B is having issues with: Hey gang, I'm getting a very strange error, or lack of error rather, in a bit of code that seemingly looks fine. The goal is to print "f... More on teamtreehouse.com
🌐 teamtreehouse.com
2
April 2, 2019
Java: Comparing strings using == instead of string.equals()
== doesn't check the contents of the 2 strings, it checks if they are the same object. More on reddit.com
🌐 r/learnprogramming
7
1
August 5, 2018
🌐
CodeGym
codegym.cc › java blog › java objects › java compare strings
Compare String and Equals comparisons in Java
April 2, 2025 - It overrides the equals() method. And instead of comparing references, it compares the sequence of characters in the strings. If the text is the same, then it doesn't matter how they were created or where they are stored: whether in the string pool or a separate area of memory. The result of the comparison will be true. By the way, Java lets you perform case-insensitive string comparisons.
🌐
Coderanch
coderanch.com › t › 408473 › java › String-equals-regex
String.equals() versus regex (Beginning Java forum at Coderanch)
October 17, 2007 - Sounds improbable. Surely, to compare strings for exact equality, you have to compare every character, and regular expressions cannot help. A regular expression might be faster for more-sophisticated string comparisons, but not for exact equality, I think. If you happened to know that certain parts of the string were more likely to differ than others, then you might win with a carefully-constructed regex, I suppose.
🌐
Sentry
sentry.io › sentry answers › java › how to compare strings in java
How to compare strings in Java | Sentry
The Problem How do I compare strings in Java? The Solution To compare strings in Java for equality, you should use String.equals() . Output: If uppercase and…
🌐
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 ...
🌐
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
🌐
TechVidvan
techvidvan.com › tutorials › java-string-equals-method
Java String equals() Method - TechVidvan
March 18, 2024 - Java String equals() compares two strings based on their data/content. It is used particularly to compare the contents of two String objects in the context of the String.
🌐
TutorialsPoint
tutorialspoint.com › java-string-comparison-differences-between-equals-matches-compareto
Java String comparison, differences between ==, equals, matches, compareTo().
The string is checked against the entire regular expression. Unlike equals(), it can perform more complex comparisons such as matching specific patterns (e.g., email addresses, phone numbers, etc.).
🌐
DEU University
web.deu.edu.tr › doc › oreily › java › langref › ch04_09.htm
[Chapter 4] 4.9 Equality Comparison Operators
Because the == operator determines if two objects are the same object, it is not appropriate for comparisons that need to determine if two objects have the same contents. For example, if you need to know whether two String objects contain the same sequences of characters, the == operator is inappropriate. You should use the equals() method instead:[4]
🌐
W3Schools
w3schools.com › java › ref_string_equals.asp
Java String equals() Method
Operators Arithmetic Assignment Comparison Logical Precedence Code Challenge Java Strings
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › lang › String.html
String (Java Platform SE 8 )
October 20, 2025 - Constructs a new String by decoding the specified array of bytes using the specified charset. The length of the new String is a function of the charset, and hence may not be equal to the length of the byte array.
🌐
Udemy
blog.udemy.com › home › understanding the java string equals method
Understanding the Java String Equals Method - Udemy Blog
December 4, 2019 - Java String Equals method is an instance method that allows comparing two string objects or literal for equality. The String Equals method is called on the String type object that has to be compared for equality.
🌐
Quora
quora.com › Is-It-bad-to-use-equals-instead-of-when-comparing-strings-in-Java
Is It bad to use .equals() instead of == when comparing strings in Java? - Quora
Answer (1 of 38): Actually, that’s preferable, assuming the most common sense of “equals,” which most assume means that the two strings have the same value—and conversely, if a.equals(b) is false, then a and b do NOT have the same value. == only compares the memory locations of the strings.
🌐
Baeldung
baeldung.com › home › java › java string › comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - As String is one of the most used data types in Java, this is naturally a very commonly used operation. 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.
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-equals-compareto-equalsignorecase-and-compare
Java | ==, equals(), compareTo(), equalsIgnoreCase() and compare() - GeeksforGeeks
January 22, 2026 - Comparisons between s1, s2, and ... a different object in memory. Therefore, s1 == s4 returns false. The equals() method compares the content of two strings....
🌐
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.
Top answer
1 of 9
92

I guess it's just consistency, or "principle of least astonishment". String is an object, so it would be surprising if was treated differently than other objects.

At the time when Java came out (~1995), merely having something like String was total luxury to most programmers who were accustomed to representing strings as null-terminated arrays. String's behavior is now what it was back then, and that's good; subtly changing the behavior later on could have surprising, undesired effects in working programs.

As a side note, you could use String.intern() to get a canonical (interned) representation of the string, after which comparisons could be made with ==. Interning takes some time, but after that, comparisons will be really fast.

Addition: unlike some answers suggest, it's not about supporting operator overloading. The + operator (concatenation) works on Strings even though Java doesn't support operator overloading; it's simply handled as a special case in the compiler, resolving to StringBuilder.append(). Similarly, == could have been handled as a special case.

Then why astonish with special case + but not with ==? Because, + simply doesn't compile when applied to non-String objects so that's quickly apparent. The different behavior of == would be much less apparent and thus much more astonishing when it hits you.

2 of 9
31

James Gosling, the creator of Java, explained it this way back in July 2000:

I left out operator overloading as a fairly personal choice because I had seen too many people abuse it in C++. I've spent a lot of time in the past five to six years surveying people about operator overloading and it's really fascinating, because you get the community broken into three pieces: Probably about 20 to 30 percent of the population think of operator overloading as the spawn of the devil; somebody has done something with operator overloading that has just really ticked them off, because they've used like + for list insertion and it makes life really, really confusing. A lot of that problem stems from the fact that there are only about half a dozen operators you can sensibly overload, and yet there are thousands or millions of operators that people would like to define -- so you have to pick, and often the choices conflict with your sense of intuition.

🌐
Stanford
web.stanford.edu › class › archive › cs › cs108 › cs108.1082 › 106a-java-handouts › HO38Strings.pdf pdf
CS106A, Stanford Handout #38 Fall, 2004-05 Nick Parlante Strings and Chars
If we have two string objects, we use the equals() method to check if they are the same. In Java, we always use the equals() message to compare two objects – strings are just an
🌐
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 - Getting to know the String class in java took me some time. In general both the equals() method and “==” operator in Java are used to compare objects to check equality but the ‘’==’ operator’ checks if both objects point to the same memory location whereas the equals() method evaluates the values inside the objects.