Python's str class uses value-equality for its __eq__ method. In Python, classes can override __eq__ to define how == behaves.

Contrast that with Java where == always does reference-equality. In Java, == will only return true if both objects are literally the same object; regardless of their content. Java's == is more comparable to Python's is operator.

A better comparison, as noted in the comments, would be to compare these:

"a".equals("a")  // Java

"a" == "a"  # Python

Java's String class has its equals do a value equality instead of of reference equality.

Answer from Carcigenicate on Stack Overflow
🌐
Medium
medium.com › @shreyagoswami0307 › decoding-the-difference-between-python-and-java-string-equality-62ca068344f1
Decoding the Difference Between Python and Java String Equality | by Shreya Goswami | Medium
February 20, 2024 - In Python, the == operator is overloaded for string comparison, and it checks for value equality. This operator compares the content of the strings, ensuring that they have the same characters in the same order. str1 = "hello" str2 = "hello" ...
Top answer
1 of 3
4

Python's str class uses value-equality for its __eq__ method. In Python, classes can override __eq__ to define how == behaves.

Contrast that with Java where == always does reference-equality. In Java, == will only return true if both objects are literally the same object; regardless of their content. Java's == is more comparable to Python's is operator.

A better comparison, as noted in the comments, would be to compare these:

"a".equals("a")  // Java

"a" == "a"  # Python

Java's String class has its equals do a value equality instead of of reference equality.

2 of 3
1

In python == is used to compare the content of the objects by overriding the operator.eq(a, b) method, str class has overridden this in order to compare the content of objects

These are the so-called “rich comparison” methods. The correspondence 
between operator symbols and method names is as follows: x<y calls 
x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls 
x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y).

But in java == operator is used compare the reference of objects here

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.

so in java to compare the content of object you have to use equals which is overridden in String class.

if (str1.equals(str2))

so java == operator is equal to is operator in python which compare both references are pointed to same object or not

🌐
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 ?

Top answer
1 of 4
679

For all built-in Python objects (like strings, lists, dicts, functions, etc.), if x is y, then x==y is also True.

Not always. NaN is a counterexample. But usually, identity (is) implies equality (==). The converse is not true: Two distinct objects can have the same value.

Also, is it generally considered better to just use '==' by default, even when comparing int or Boolean values?

You use == when comparing values and is when comparing identities.

When comparing ints (or immutable types in general), you pretty much always want the former. There's an optimization that allows small integers to be compared with is, but don't rely on it.

For boolean values, you shouldn't be doing comparisons at all. Instead of:

if x == True:
    # do something

write:

if x:
    # do something

For comparing against None, is None is preferred over == None.

I've always liked to use 'is' because I find it more aesthetically pleasing and pythonic (which is how I fell into this trap...), but I wonder if it's intended to just be reserved for when you care about finding two objects with the same id.

Yes, that's exactly what it's for.

2 of 4
284

I would like to show a little example on how is and == are involved in immutable types. Try that:

a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True

is compares two objects in memory, == compares their values. For example, you can see that small integers are cached by Python:

c = 1
b = 1
>>> b is c
True

You should use == when comparing values and is when comparing identities. (Also, from an English point of view, "equals" is different from "is".)

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.

🌐
Delft Stack
delftstack.com › home › howto › java › java string equals vs
Comparison Between string.equals() vs == in Java | Delft Stack
March 11, 2025 - PythonPython PandasNumpyScipyJavaScript · Rashmi Patidar Mar 11, 2025 Java Java String · Understanding string.equals() Understanding == Operator · When to Use Each Method · Conclusion · FAQ · Java, a widely-used programming language, has its own unique way of handling strings.
🌐
W3Schools
w3schools.com › java › ref_string_equals.asp
Java String equals() Method
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically. ... If you want to use W3Schools services as an educational institution, ...
Find elsewhere
🌐
JetBrains
jetbrains.com › help › inspectopedia › StringEquality.html
String comparison using '==', instead of 'equals()' | Inspectopedia Documentation
Reports code that uses of == or != to compare strings. These operators determine referential equality instead of comparing content.
Top answer
1 of 15
1695

is is identity testing, and == is equality testing. What happens in your code would be emulated in the interpreter like this:

>>> a = 'pub'
>>> b = ''.join(['p', 'u', 'b'])
>>> a == b
True
>>> a is b
False

So, no wonder they're not the same, right?

In other words: a is b is the equivalent of id(a) == id(b)

2 of 15
672

Other answers here are correct: is is used for identity comparison, while == is used for equality comparison. Since what you care about is equality (the two strings should contain the same characters), in this case the is operator is simply wrong and you should be using == instead.

The reason is works interactively is that (most) string literals are interned by default. From Wikipedia:

Interned strings speed up string comparisons, which are sometimes a performance bottleneck in applications (such as compilers and dynamic programming language runtimes) that rely heavily on hash tables with string keys. Without interning, checking that two different strings are equal involves examining every character of both strings. This is slow for several reasons: it is inherently O(n) in the length of the strings; it typically requires reads from several regions of memory, which take time; and the reads fills up the processor cache, meaning there is less cache available for other needs. With interned strings, a simple object identity test suffices after the original intern operation; this is typically implemented as a pointer equality test, normally just a single machine instruction with no memory reference at all.

So, when you have two string literals (words that are literally typed into your program source code, surrounded by quotation marks) in your program that have the same value, the Python compiler will automatically intern the strings, making them both stored at the same memory location. (Note that this doesn't always happen, and the rules for when this happens are quite convoluted, so please don't rely on this behavior in production code!)

Since in your interactive session both strings are actually stored in the same memory location, they have the same identity, so the is operator works as expected. But if you construct a string by some other method (even if that string contains exactly the same characters), then the string may be equal, but it is not the same string -- that is, it has a different identity, because it is stored in a different place in memory.

🌐
Programiz
programiz.com › java-programming › examples › differentiate-string-equals
Java Program to Differentiate String == operator and equals() method
== checks if the reference to string objects are equal or not. Here, name1 and name2 are two different references.
🌐
Reddit
reddit.com › r/learnjava › confused on == vs .equals()
r/learnjava on Reddit: Confused on == vs .equals()
November 8, 2020 -

I already know that == is used to check for location, whereas .equals() is used to check for value, which makes me really confused on this if statement https://pastebin.com/9Vv4hCnu:

if (this.artist == comparedSong.artist &&

this.name.equals(comparedSong.name) &&

this.durationInSeconds == comparedSong.durationInSeconds){

return true;

}

How come I'm able to use both .equals() and == and it will yield the same result? I thought == would just not do anything (since I already checked to see if the parameters are in the same location) but if I change this.artist or this.durationInSeconds to something different than comparedSong.artist or comparedSong.durationInSeconds, it returns it as false.

🌐
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

🌐
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 ... if a.equals(b) is false, then a and b do NOT have the same value. == only compares the memory locations of the strings....
🌐
Processing
processing.org › reference › string_equals_
equals() / Reference - String
String str1 = "CCCP"; String str2 = "CCCP"; // Tests to see if 'str1' is equal to 'str2' if (str1.equals(str2) == true) { println("Equal"); // They are equal, so this line will print } else { println("Not equal"); // This line will not print }
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.