Re: String comparison with "==" is not reliable?
- From: "maxnesler@xxxxxxxxx" <maxnesler@xxxxxxxxx>
- Date: Thu, 29 Nov 2007 11:56:54 -0800 (PST)
On Nov 29, 2:21 pm, Owen Jacobson <angrybald...@xxxxxxxxx> wrote:
On Nov 29, 11:17 am, www <w...@xxxxxxxxxx> wrote:
I have just tested the following code:
String str1="Hello";
String str2="Hello";
if(str1 == str2)
{
System.out.println("equal");}
else
{
System.out.println("Not equal");
}
Guess what? It prints out "equal".
And if you took ten minutes to read the JLS, you'd understand why.
String constant expressions are interned as if by
String.intern(String), meaning that all identical string constants in
the source refer to the same object at runtime. Since == compares two
references and evaluates to true if they refer to the same object,
"foo" == "foo" will always evaluate to true.
The same can't be said if either or both strings did not come from
literals, since equal strings may be represented by non-identical
objects.- Hide quoted text -
- Show quoted text -
Just to make it easy:
Your test is "equal" because the strings contain the same content.
Java does this to save space.
.
- Follow-Ups:
- Re: String comparison with "==" is not reliable?
- From: Joe Attardi
- Re: String comparison with "==" is not reliable?
- References:
- String comparison with "==" is not reliable?
- From: www
- Re: String comparison with "==" is not reliable?
- From: www
- Re: String comparison with "==" is not reliable?
- From: Owen Jacobson
- String comparison with "==" is not reliable?
- Prev by Date: Re: Auto serialize/unserialize on JPA
- Next by Date: Java J2EE Openings in Phoenix, AZ, Client Will Relocate
- Previous by thread: Re: String comparison with "==" is not reliable?
- Next by thread: Re: String comparison with "==" is not reliable?
- Index(es):
Relevant Pages
|