Here we will discuss How The Result By == Is Different From equals() In Java? As both are used for comparing two variables or quantities but one refers to its memory and the other to the value of that variable. Let’s understand each with the help of some examples.
equals () Operator
As we know equals() is used for comparing the values of two objects whether they have the same value or not as it results in a boolean output where we get the answer in True or false.
Let’s understand it in a better manner with an example
public class Test { public static void main(String[] args) { String s1 = "HELLO"; String s2 = "HELLO"; String s3 = new String("HELLO"); System.out.println(s1 == s2); // true System.out.println(s1 == s3); // false System.out.println(s1.equals(s2)); // true System.out.println(s1.equals(s3)); // true } } OUTPUT of Above will be true false true true
Here are all the possible examples that could we be there objects s1 and s2 both refer to the same object and have the same values so here we can say both will give true in case of .equals Similarly s1 and 3 have the same values so it is giving the answer as true when we use .equals.
Now Let’s understand == operators.
== Operators
This Operator is used for comparing the reference of objects then it will result in true otherwise it will be false. As we can see in the example above how it is giving output as true when s1 and s2 are being compared as both of them refers to the same object.
Whereas in the case of s1 and s3 it results in false, although both have the same value which is “HELLO” but s3 refers to another location of memory so it is resulting as false.
Learn More about How The Result By == Is Different From equals() In Java? equals to
And also Visit Java Tutorials By Prakhar Yadav to get more answers to different problems in java and also visit Python’s list: What is the difference Between methods Append and Extend? to learn more about Python and other tutorials.