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");
}
}
}
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