+ 4
What is the difference between equals () and ==?
4 Answers
+ 5
From my understanding, == compares references whereas equals compares values.
+ 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'
+ 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.Â
+ 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