Thursday, 23 May 2019

Java: String equals vs compareTo


We can figure out the differences between equals and comapreTo methods, by looking at the source code.

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }
    if (anObject instanceof String) {
        String anotherString = (String)anObject;
        int n = value.length;
        if (n == anotherString.value.length) {
            char v1[] = value;
            char v2[] = anotherString.value;
            int i = 0;
            while (n-- != 0) {
                if (v1[i] != v2[i])
                    return false;
                i++;
            }
            return true;
        }
    }
    return false;
}

public int compareTo(String anotherString) {
    int len1 = value.length;
    int len2 = anotherString.value.length;
    int lim = Math.min(len1, len2);
    char v1[] = value;
    char v2[] = anotherString.value;

    int k = 0;
    while (k < lim) {
        char c1 = v1[k];
        char c2 = v2[k];
        if (c1 != c2) {
            return c1 - c2;
        }
        k++;
    }
    return len1 - len2;
}

a. From the source code, it is clear that, compareTo method compares two strings lexicographically (based on unicode value of each character in the strings), where as equals method checks whether two strings have same content or not.

b. str1.equals((String)null) return false, where as str1.compareTo((String)null) throws NullPointerException


App.java

package com.sample.app;

public class App {
    public static void main(String args[]) {
        String str1 = "Hello World";
        
        System.out.println("str1.equals((String)null) : " + str1.equals((String)null));
        System.out.println("str1.compareTo((String)null) : " + str1.compareTo((String)null));
    }
}

Output
str1.equals((String)null) : false
Exception in thread "main" java.lang.NullPointerException
    at java.lang.String.compareTo(String.java:1155)
    at com.sample.app.App.main(App.java:8)


You may like




No comments:

Post a Comment