Java - String String Comparison

Introduction

String class overrides the equals() method to compare two strings for equality based on their contents.

equals() method

For example, you can compare two strings for equality, as shown:

String str1 = new String("Hello");
String str2 = new String("Hi");
String str3 = new String("Hello");

boolean b1, b2;

b1 = str1.equals(str2); // false will be assigned to b1
b2 = str1.equals(str3); // true will be assigned to b2

You can also compare string literals with string literals or string objects, as shown:

b1 = str1.equals("Hello");  // true will be assigned to b1
b2 = "Hello".equals(str1);  // true will be assigned to b2
b1 = "Hello".equals("Hi");  // false will be assigned to b1

== operator

The == operator always compares the references of two objects in memory.

For example, str1 == str2 and str1 == str3 will return false, because str1, str2 and str3 are references of three different String objects in memory.

compareTo() method

The new operator always returns a new object reference.

To compare two strings based on the Unicode values of their characters, use the compareTo() method.

Its signature is

public int compareTo(String anotherString)

It returns an integer, which can be 0 (zero), a positive integer, or a negative integer.

If any two characters differ in their Unicode values, the method returns the difference between the Unicode values of those two characters.

For example, "a".compareTo("b") will return -1.

The Unicode value is 97 for a and 98 for b. It returns the difference 97 - 98, which is -1.

The following are examples of string comparisons:

"abc".compareTo("abc") will return 0
"abc".compareTo("xyz") will return -23 (value of 'a' - 'x')
"xyz".compareTo("abc") will return 23 (value of 'x' - 'a')

Note

compareTo() method compares two strings based on the Unicode values of their characters.

To perform language-based string comparisons, you should use the compare() method of the java.text.Collator class instead.

Demo

public class Main {
  public static void main(String[] args) {
    String apple = new String("A");
    String smallApple = new String("a");

    System.out.println(apple.equals(smallApple));
    System.out.println(apple.equals(apple));
    System.out.println(apple == apple);
    System.out.println(apple == smallApple);
    System.out.println(apple.compareTo(apple));
    System.out.println(apple.compareTo(smallApple));
  }// w  w w.  jav a 2 s.  c  om
}

Result

Related Topics

Exercise