Learn Java: How do I compare two Strings with Java
Developer's Daily Java Q&A Center
  main | java | perl | unix | dev directory | web log
   
Main
Java
Education
Java Q&A Center


Question: How do I compare two Strings to each other?
Answer:  

Here's the right way to do it:

You should use one of the following tests to compare the contents of two strings:

if (string1.equals(string2))
if (string1.compareTo(string2) < 0)
if (string1.equalsIgnoreCase(string2))

Any of these statements compare the contents of the two strings name string1 and string2. There are other ways to compare the contents of two Strings, but these are the most-frequently used methods I'm aware of.


Here's the wrong way to do it:

Many times we make the mistake of using the following syntax when comparing strings:

        if (string1 == string2)

A comparison of objects (such as Strings) using the == operator doesn't compare the contents of the Strings. Instead, it compares the address of the two Strings.

 


Read the BLOG

Copyright © 1998-2002 DevDaily Interactive, Inc.
All Rights Reserved.