Reputation: 19
In Java, when for example you say string1.compareTo(string2), how is the compareTo method accessing the string1. I see the method takes in the second string but how does it compare it to the first if it is not getting passed along?
Upvotes: 0
Views: 107
Reputation: 3585
I think this little 'illustration' could help you
Class String {
public int CompareTo(String string2)
{
if (this==string2) return 1; //The == is completely wrong here but it gives you an idea on how it works
else return 0;
}
}
When you call string1.CompareTo(string2);
in the method, this
will reference the object itself, so here it references string1
Upvotes: -1
Reputation: 4252
compareTo() is a member function of Class String, this means that for invoking this function you need an Object of Type String. So when you say string1.compareTo(string2) , this means that you are invoking compareTo() function on the String object 'string1' and passing 'string2' as the argument.
Upvotes: 2