Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2007

Tip: Looking for answers? Try searching our database.

String comparison with "==" is not reliable?

Thread view: 
www - 29 Nov 2007 18:46 GMT
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().equals(str2.trim()))
{
    System.out.println("equal");
}
else
{
    System.out.println("Not equal");
}

Can you give me some hint? Thank you.
maxnesler@gmail.com - 29 Nov 2007 19:08 GMT
> Hi,
>
[quoted text clipped - 32 lines]
>
> Can you give me some hint? Thank you.

"==" will test true if they are the same object.
www - 29 Nov 2007 19:17 GMT
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".
Owen Jacobson - 29 Nov 2007 19:21 GMT
> I have just tested the following code:
>
[quoted text clipped - 12 lines]
>
> 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.
maxnesler@gmail.com - 29 Nov 2007 19:56 GMT
> > I have just tested the following code:
>
[quoted text clipped - 26 lines]
>
> - 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.
Joe Attardi - 29 Nov 2007 20:58 GMT
> Your test is "equal" because the strings contain the same content.
> Java does this to save space.

Not quite... this is an oversimplification. Consider this:

String str1 = "Joe";
String str2 = "Joe";
System.out.println(str1 == str2); // prints "true"

String str1 = new String("Joe");
String str2 = new String("Joe");
System.out.println(str1 == str2); // prints "false"

In both cases the Strings contain the same content. But in the first
example, they are the exact same object (because, as Owen pointed out,
string constants are interned). So the == operator returns true.

In the second example, though, we're forcing the Strings to be two
separate objects. This time they do not refer to the same object.

Just tested on 1.5.0_13.
Patricia Shanahan - 29 Nov 2007 20:00 GMT
> I have just tested the following code:
>
[quoted text clipped - 11 lines]
>
> Guess what? It prints out "equal".

"==" is absolutely reliable for testing whether two references are
either both null, or both point to the same object. There is only one
copy of each String constant expression, such as "Hello". Initializing
str1 and str2 by assignment of the same String literal ensures they
reference the same object.

"==" and ".equals" have the same behavior if the two expressions
reference the same object, or if they reference String objects with
different values. The important case for deciding which to use is what
behavior you want if str1 and str2 reference two distinct String objects
that have the same content. If you want that case to be "true" use
".equals". If you want it to be "false" use "==".

Patricia
Roedy Green - 30 Nov 2007 07:49 GMT
>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.

see http://mindprod.com/jgloss/string.html
for an explanation. You can sometimes use == but most of the time you
must use equals.
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.