arjun
arjun

Reputation: 307

Why is there a "==" inside String.equals?

Why Java is comparing (this == another String) inside equalsIgnoreCase method for checking a string insensitive?

Also, String equals is comparing (this == another String) to compare two objects?

Java 6: String Class equalsIgnoreCase implementation given below.

 public boolean equalsIgnoreCase(String anotherString) {
        return (this == anotherString) ? true :
               (anotherString != null) && (anotherString.count == count) &&
           regionMatches(true, 0, anotherString, 0, count);
    }

Java 6: String Class equals implementation given below.

 public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }

Upvotes: 3

Views: 219

Answers (3)

Bohemian
Bohemian

Reputation: 425128

== is true when comparing with the same object - given an efficiency increase more likely than just about any other class due to String interning.

Note that this code:

return (this == anotherString) ? true : <rest of line>

could have been written (more elegantly IMHO) as:

return this == anotherString || <rest of line>

Upvotes: 2

Saif
Saif

Reputation: 7052

 this == another object 

This is the basic check in equals method for almost all Objects not just in String class. It is efficient and also a good practice to check this first in your own Class.
The logic is simple if both have the same reference then they are referring to the same object always, so they are equal.

You don't need any other comparison to tell they are equal for sure if this == another object is true.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1501626

Why Java is comparing (this == another String) inside equalsIgnoreCase method for checking a string insensitive?

It's an optimization. If the reference passed in is exactly the same as this, then equals must return true, but we don't need to look at any fields etc. Everything is the same as itself. From the documentation for Object.equals(Object):

The equals method implements an equivalence relation on non-null object references:

  • It is reflexive: for any non-null reference value x, x.equals(x) should return true.
  • ...

It's very common for an equality check to start with:

  • Is the other reference equal to this? If so, return true.
  • Is the other reference null? If so, return false.
  • Does the other reference refer to an object of the wrong type? If so, return false.

Then you go on to type-specific checks.

Upvotes: 10

Related Questions