What is the difference between equals () and ==? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 4

What is the difference between equals () and ==?

9th Feb 2018, 4:19 PM
FASALU RAHMAN KP
FASALU RAHMAN KP - avatar
4 Answers
+ 5
From my understanding, == compares references whereas equals compares values.
9th Feb 2018, 4:21 PM
Fata1 Err0r
Fata1 Err0r - avatar
+ 4
I'll explain with example String s1 = "hi"; String s2 = "hi"; if(s1==s2) System.out.print("== works"); if(s1.equals(s2)) System.out.priny("equals works"); output will be - equals works. == compares reference equals() compares value (text) Inside those strings hence, whenever you want to compare strings use eauals method'
9th Feb 2018, 4:29 PM
code learner
code learner - avatar
+ 3
-> Equals() method is defined in Object class in Java and used for checking equality of two objects defined by business logic e.g. two Employees are considered equal if they have sameempId etc. You can have your domain object and then override equals method for defining a condition on which two domain objects will be considered equal.  -> "==" or equality operator in Java is a binary operator provided by Java programming language and used to compare primitives and objects. In terms of comparing primitives likeboolean, int, float "==" works fine but when it comes to comparing objects it creates confusion with equals method in Java. "==" compare two objects based on memory reference. so "==" operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false. 
9th Feb 2018, 4:33 PM
Diwakar
Diwakar - avatar
+ 2
= is assignment operator for assigning values for example a=2:; and == is for comparison or we can say comparing values for example if a==b then print equal ;;;; thank you
13th Feb 2018, 1:38 PM
Chekka.Ratna Bindu Priya
Chekka.Ratna Bindu Priya - avatar