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



On Nov 29, 1:42 pm, www <w...@xxxxxxxxxx> 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.

This morning, I found out that I was wrong.

I have two Strings, str1 and str2. They received values from some where
else. When I print them out to screen, they look same.(I am aware of
some unvisible thing, so I used trim()

//str1 and str2
if(str1.trim() == str2.trim())
{
System.out.println("equal");}

else
{
System.out.println("Not equal");

}

Above code print out "Not equal". But the following code print out "equal".

if(str1.trim().equalsIgnoreCase(str2.trim()))
{
System.out.println("equal");}

else
{
System.out.println("Not equal");

}

Can you give me some hint? Thank you.

== is reliable, but not for what you're trying to do. == compares the
object's references. .equals() compares the actual string value
(which is what most people are trying to do). This is the case with
any object. AFAIK, the only time == actually compares values is if
you're comparing primitives (ints, double, floats).
.



Relevant Pages

  • Re: Streitfrage
    ... Parameter sollten als eigene Verwendungen von Strings gezählt werden, und eine Zuweisung an Str1 oder Str2 sollte dann die lokale Variable s nicht ändern. ...
    (de.comp.lang.delphi.misc)
  • Re: sort an array of strings
    ... > These are normal strings and you can store anything in it < 100 bytes. ... Ordinary quicksort on *average* performs fewer compares and data ... moves than either heap-sort or merge-sort. ... Mergesort is the only sorting algorithm that performs ...
    (comp.lang.c)
  • Re: coding an anagram function
    ... I need to create a VBA function which compares two cells to see if the ... The cells will only contain letters, and no letter will appear more ... if the function compares two strings and gets the same addition ... are therefore anagrams of each other. ...
    (microsoft.public.excel.programming)
  • Re: Difference Between C++ and Visual C++
    ... It compares pointers to those strings. ... What the pointer values are depends on where exactly in memory the strings ... that the program sends an angry e-mail to president Bush, ...
    (comp.lang.cpp)
  • Re: Substring check within VBA
    ... (remove nothere from the email address if mailing direct) ... > If Str1 and Str2 are strings, is there a function or simple coding within ... > to return TRUE if Str1 is a substring of Str2, ...
    (microsoft.public.excel.programming)