Home Java Java-tips Data Strings String Comparison

Ask Questions?

View Latest Questions

Advertisement


 
 

String Comparison
Posted on: July 26, 2006 at 12:00 AM
Comparing Strings: ==, .equals(), .compareTo(), ...

Java Notes

String Comparison

Strings can not be compared with the usual <, <=, >, or >= operators, and the == and != operators don't compare the characters in the strings.

Comparing objects vs. primitive types

[to be supplied]

Comparing Strings: ==, .equals(), .compareTo(), ...

To compare Strings for equality, don't use ==. The == operator checks to see if two objects are exactly the same object. Two strings may be different objects, but have the same value (have exactly the same characters in them). Use the .equals() method to compare strings for equality. Similarly, use the .compareTo() method to test for unequal comparisons. For example,
    String s = "something", t = "maybe something else";
    if (s == t)      // Legal, but usually WRONG.
    if (s.equals(t)) // RIGHT
    if (s > t)    // ILLEGAL
    if (s.compareTo(t) > 0) // CORRECT>

Comparing without regard to case

[to be supplied]
Copyleft 2003 Fred Swartz MIT License, Last update: 2000-11-10
Advertisement


DMCA.com