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.
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.
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
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.
There are two ways to do this. The first is to use the operator module, which contains functions for all of the mathematical operators:
>>> from operator import eq
>>> x = "a"
>>> y = "a"
>>> eq(x, y)
True
>>> y = "b"
>>> eq(x, y)
False
>>>
The other is to use the __eq__ method of a string, which is called when you use ==:
>>> x = "a"
>>> y = "a"
>>> x.__eq__(y)
True
>>> y = "b"
>>> x.__eq__(y)
False
>>>
You could do:
import operator
a = "string1"
b = "string2"
print operator.eq(a, b)
This is similar to Java in that you're not using an explicit operator.
However in Java you're using a method call on the String class (i.e., myString.equals(otherString)) but in Python eq is just a function which you import from a module called operator (see operator.eq in the documentation).
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.
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".)
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.
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)
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.
I thought that Python was different from other OOP languages like Java and C++ in that it implements equality of strings by comparing their value. But I've been reading that Python actually compares strings by their address, so the == shouldn't be used for value comparison. But from my own testing, == seems to work just fine for value comparison...
So does == compare value or address (or some other property of objects, like ID or something) of two objects?
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.
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
I suspect that this originates from a safety precaution used when programming in older C (or C++). In C, you could accidentally assign a value when you mean to test equality:
if (x = 3)
This condition will always be true, since it's assignment x a value of 3, not testing that x is equal to 3. To avoid this subtle bugs, developers started reversing the condition:
if (3 = x)
This contains the same "bug", but will generate a compiler error, so it's safer.
More modern languages don't have this problem, and they can easily warn you when you try to do these sorts of things. As such, it's no pretty much pure preference, so pick one, and use it consistently.
Standard and good practice would vary with a culture of an organisation you are working for
Our standard in .NET is
myStringVar == "myString"simply because we have agreed on it, i.e. we believe it to be clean and concsice
Note: This does not apply to Java due to == comparing the references instead of the objects themselves. In Java you should be using myStringVar.equals("myString").
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.
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.