Re: String comparison with "==" is not reliable?
- From: Jason Cavett <jason.cavett@xxxxxxxxx>
- Date: Thu, 29 Nov 2007 11:02:31 -0800 (PST)
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).
.
- Follow-Ups:
- References:
- Prev by Date: String comparison with "==" is not reliable?
- Next by Date: Re: Is this code "proper" use of extend?
- Previous by thread: String comparison with "==" is not reliable?
- Next by thread: Re: String comparison with "==" is not reliable?
- Index(es):
Relevant Pages
|