I've got a Python program where two variables are set to the value 'public'
. In a conditional expression I have the comparison var1 is var2
which fails, but if I change it to var1 == var2
it returns True
.
Now if I open my Python interpreter and do the same "is" comparison, it succeeds.
>>> s1 = 'public' >>> s2 = 'public' >>> s2 is s1 True
What am I missing here?
In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .
We can compare String in Java on the basis of content and reference. It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc. There are three ways to compare String in Java: By Using equals() Method.
compare() is a public member function of string class. It compares the value of the string object (or a substring) to the sequence of characters specified by its arguments. The compare() can process more than one argument for each string so that one can specify a substring by its index and by its length.
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.
is
is identity testing, ==
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With