javacodex.com
Java Examples
Java Examples
memu home questions

How do I compare strings in Java?

Use equals() or compareTo() to test for value equality.

The method boolean equals(Object anObject) Returns true if and only if the argument is a String object that represents the same sequence of characters as this object.

The method int compareTo(String anotherString) Compares two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.

Use == to test for reference equality.

TestString.java

public class TestString {
   public static void main(String[] args) {
 
      String string1 = new String("foo");
      String string2 = new String("foo");
      String string3 = new String("bar");
      String string4 = string3;
 
      System.out.println("string1.equals(string2): " + string1.equals(string2) );
      System.out.println("string2.equals(string3): " + string2.equals(string3) );
      System.out.println("string3.equals(string4): " + string3.equals(string4) );
 
      System.out.println("string1.compareTo(string2): " + string1.compareTo(string2) );
      System.out.println("string2.compareTo(string3): " + string2.compareTo(string3) );
      System.out.println("string3.compareTo(string4): " + string3.compareTo(string4) );
      System.out.println();
 
      System.out.println("string1 == string2: " + (string1 == string2) );
      System.out.println("string2 == string3: " + (string2 == string3) );
      System.out.println("string3 == string4: " + (string3 == string4) );
 
      string4 = string4 + "more stuff";
      System.out.println("string3 == string4: " + (string3 == string4) );
   }
}
 

Output

$ java TestString
string1.equals(string2): true
string2.equals(string3): false
string3.equals(string4): true

string1.compareTo(string2): 0
string2.compareTo(string3): 4
string3.compareTo(string4): 0

string1 == string2: false
string2 == string3: false
string3 == string4: true

string3 == string4: false

Questions answered by this page:

How do I compare strings in Java? How to compare Java Strings String Comparison in Java How to use equals() and compareTo() on Strings?




Contact: javacodex@yahoo.com