Re: String comparison with "==" is not reliable?



www wrote:
Hi,

I always thought I can use "==" to compare if two Strings are equal(with same case too). I know there is a method .equals(Object o) or equalsIgnoreCase(String s). But I always thought "==" is good enough.

== is equals in the sense of "they point to the same object." There are only three times you can guarantee this with Strings:

1. String literals are equal.
2. Internal String representations (i.e., str1.intern()) are equal.
2a. This will print true (i.e., the intern of a String literal is itself):
public class StringTest {
public final static void main(String... args) {
String str1 = "hello";
String str2 = new String(str1);
System.out.println(str1 == str2.intern());
}
}
3. The two objects were assigned to each other or to a common object at some point in time.

Any time a String does not meet any of these two requirements the equals sign will return false.

--
Beware of bugs in the above code; I have only proved it correct, not tried it. -- Donald E. Knuth
.



Relevant Pages

  • Re: Function that returns date of file.
    ... string after the date/time when it is used by itself. ... Is that your entire script? ... I make an IF statement that required the 'equals equals'. ... designed database your job will be all that much harder. ...
    (alt.php)
  • Re: == versus .Equals()
    ... whether you use the == operator or the Equals method. ... To explain the differences I will use the String class as an example. ... the String class uses the static Equals method ... a string compare. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Catching invalid string comparisons
    ... the programmer expected it to check if it is equal to an empty string. ... compares for equality -- but two references are equal ... Comparing the objects themselves, ... requires use of the equals() method. ...
    (comp.lang.java.programmer)
  • Re: hashCode() for Custom classes
    ... I am currently faced with the task of providing a logical equals() ... have to override the hashCode() so that when an object of this class ... String name; ... The hash code of Agent is the combined hash code of ...
    (comp.lang.java.programmer)
  • Re: Compare Two Structure Data Types...
    ... I normally override & overload the Equals method on the Structure to do the ... If I overloaded Equals in A for B, I would also overload Equals in B for A, ... > Public LastName as String ... > Public City as String ...
    (microsoft.public.dotnet.languages.vb)