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



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.
.



Relevant Pages

  • Re: String comparison with "==" is not reliable?
    ... And if you took ten minutes to read the JLS, ... String constant expressions are interned as if by ... the source refer to the same object at runtime. ... since equal strings may be represented by non-identical ...
    (comp.lang.java.programmer)
  • Re: Debug Assertion Failure on gets(char) function
    ... Richard Heathfield wrote: ... It is sometimes useful to "intern" strings, that is, ensure that there ... high chance that equal strings would have come from the same source and ...
    (comp.lang.c)
  • Re: First position two strings differ
    ... > value should be 0 if the strings differ from the beginning. ... So your @+ approach wont return -1 on equal strings. ... To handle strings that differ at the first character, ...
    (comp.lang.perl.misc)
  • Regex help: delete text only if not within quotation marks
    ... After substitution, strings 1&3 should remain unmodified, strings 2&4 should ... equal strings 1&3 respectively. ... Additional testcase is comment ...
    (comp.lang.perl.misc)
  • Re: comparing Unicode and string
    ... any string constant that cannot be decoded using ... sys.getdefaultencodingshould be considered a kind of syntax error. ... Python strings are *byte strings* and bytes have values in the range ...
    (comp.lang.python)