Reputation:
In java there is a string class method that works as seen bellow. But I wonder how is it that we are able to call the method on a random variable of type string?
String word = "hello"
word.equals("hello");
output is true
Upvotes: 1
Views: 361
Reputation: 1695
equals method compares the string on which the method is called with the string which is passed as a parameter.
Take a look at these links:
Overriding equals in String class
Upvotes: 1
Reputation: 3755
The equals()
method is used to verify if the state of the instances of two Java classes is the same. Because equals()
is from the Object class, every Java class inherits it. But the equals()
method has to be overridden to make it work properly. Of course, String overrides equals()
.
Take a look:
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String aString = (String)anObject;
if (coder() == aString.coder()) {
return isLatin1() ? StringLatin1.equals(value, aString.value)
: StringUTF16.equals(value, aString.value);
}
}
return false;
}
As you can see, the state of the String class value has to be equals() and not the object reference. It doesn’t matter if the object reference is different; the state of the String will be compared
I have taken it from here. Better if you have an idea about String pool also. So please refer the link
Upvotes: 4
Reputation: 173
String class (String in Java is Object) inherited equals method from Object and override it as is correctly mentioned in answers by Sand and Armine.
We can call methods on String (even on constant String, statement: "Hello World".length() returns 11) because String is an Object and not a primitive type. Primitive types are byte, short, int,... You could read more about them here
Nice reading about differences between primitives types and Objects: Difference between Primitive and Reference variable in Java
Upvotes: 1
Reputation: 3051
If you are comparing String
with primitives like int,long
.
The answer is
String is not a primitive. It is a class. There are several ways to create an object from this class,
like
String word=new String("hello");
String word="hello"; //special case for String class
now word
becomes an object and you can call the method equals
(because every object you create is inherited from java.lang.Object) class.
If you look at primitives like int
.
you cannot do something like below, beacause number
is not an object.
int number=12;
number.equals(12)
Upvotes: 1