Home > Net >  Object and String parameter
Object and String parameter

Time:10-20

I am learning through w3schools. I am confused mainly about the meaning of java syntax. To my understanding, both functions the same except for the String cases. The thing I don't understand is their parameters; why is the other an Object and the other is String?

public boolean equals(Object anotherObject)
public boolean equalsIgnoreCase(String anotherString)

CodePudding user response:

equals(Object) is defined in java.lang.Object and is a method that is available on all object in Java. Therefore it's defined as generically as possible (i.e. it accepts any other object as the argument).

equalsIgnoreCase is only defined in java.lang.String. It's a specific method for comparing strings in a specific way. Since it's about text, it doesn't make sense to accept any non-String object here.

CodePudding user response:

Great question! I'm not a Java expert so don't just take my word for it :)

The equals function is declared in Object, which is the superclass of String. It is declared in a way, to support comparison to any object, not just strings.

In contrast, the equalsIgnoreCase is a function specific to just strings, it is declared in the String class. It is made for comparison between strings only.

CodePudding user response:

Only strings can have both upper and lower case, and in the case of the first one it is checking if 2 objects are equal, no matter if they are string or not so cases do not matter

  •  Tags:  
  • java
  • Related