top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

Why does String define the equals( ) method in Java? Can’t I just use ==?

+1 vote

Give proper explanation.

I am new in Java but I have knowledge about C programming.

posted Jan 28, 2016 by Nway Nadar

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

The equals() method is defined in String class in order to test whether two strings values are same sequence of characters. The method is for exclusively testing string objects, but not any other objects.

The operator ‘==’ always compares the variables but not objects. The ‘reference variables’ are compared with ‘==’, but not the objects. In terms of strings, the ‘==’ operator always compares the references and not the ‘character sequences’.

answer Jan 29, 2016 by Karthick.c
0 votes

Any class that overrides "hashcode" method from the Object class has to override "equals" method. The reason being two objects that have the same hashcode might not be equal. For ex: "STOP" & "stop" may result in the same hashcode but they are not equal.
This is the reason why String class overrides equals method because equals method allows you to test for equality of the objects.

answer Feb 7, 2016 by Ram Murthy Nagaraj
Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.