Re: String comparison with "==" is not reliable?
- From: Joshua Cranmer <Pidgeot18@xxxxxxxxxxxxxxx>
- Date: Thu, 29 Nov 2007 22:16:26 GMT
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
.
- References:
- Prev by Date: Re: JAR Creation via Ant (Adding Individual Files)
- Next by Date: Re: Array initialisation
- Previous by thread: Re: String comparison with "==" is not reliable?
- Next by thread: String comparison with "==" is not reliable?
- Index(es):
Relevant Pages
|