Reputation:
Can somebody explain to me why Python is able to print the following statement bellow while Java doesn't. I know it's something to do with == in Java and equals() but I don't really understand the difference.
Python code
str1 = "Pro"
str2 = str1 + ""
if str1 == str2:
print("the strings are equal")```
Java Code
public class StringEq {
public static void main(String[] args) {
String str1 = "Pro";
String str2 = str1 + "";
if (str1 == str2) {
System.out.println("The strings are equal");
}
}
}
Upvotes: 3
Views: 1393
Reputation: 40078
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
Upvotes: 1
Reputation: 45806
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.
Upvotes: 3
Reputation: 206
It explains it well here:
And here is a quote from that site: "We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects."
Upvotes: 1