Type conversion in String method equals in Java

211 views Asked by At

I'm having a look at Java String class and I've reached the method equals():

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

I'm wondering why is String anotherString = (String)anObject; necessary. And, moreover, if it fails, when will the type conversion fail, at compilation time or at execution time?

0

There are 0 answers