= = Operator and equals method:

  1. When the state of two objects are equal then we can say those two classes are equal. We can check equality in two ways i.e.,
    1. == operator
    2. equals()
  2. == is a Relational operator. It checks the memory location of the object
public class Student { public static void main(String[] args) { Student s1 = new student(); Student s2 = new Student(); if(s1 == s2) {
System.out.println("Equal"); memory location of object
else { System.out.println(“ Not Equal"); } } }

In the above example we create two instances for different Student classes i.e., s1 & s2 are the instances of those classes. These two instances are referring different objects i.e., address locations are different s1 is pointing 1000 location and s2 is pointing to 1001 location so addresses are different. Here we check the condition like s1 == s2 if it is True it gives output as Equal otherwise it gives Not Equal. That means if the instances are referring same address location it gives Equal otherwise Not Equal.

  1. == is mostly used for primitive data types not for Objects.
  2. Always it comparing the Two values these Two values should be same type.
public class RelationalOperator { public static void main(String[] args) { RelationalOperator r1 = new RelationalOperator(); RelationalOperator r2 = new RelationalOperator(); r1=r2;
if(r1 == r2) { memory location of object else {
System.out.println("they are not equal"); } } }

In the above example r1 & r2 are two instances of that class r1 is pointing to 1200 address location and r2 is pointing to 1201 address location after that r1 is also pointing to r2 address location only. After that we check the condition if the two are referring same address location so it gives “They are equal.

public class Examle { public static void main(String[] args) {
int s1 = 13; memory location of object int s2 = 13; if (s1 == s2) { System.out.println("Equal");
} else { System.out.println(" Not Equal "); } } }

In the above example s1,s2 are the two variables and we are initializing values for that variables like s1=13,s2=13.Then it checks s1==s2 it gives an output as “Equal” because here the values are compared

public class Equals { public static void main(String[] args) { String a = new String("geek");
String b = new String("geek"); example of equals
else { System.out.println("not equal"); } } }

The equals method checks the values, see the above example, there we are creating two instances of string with the name “geek” and “geek” , the equal method check the values which are in String object state(object state is nothing but values of object). When we use ” ==” instead of “equals” it gets printed “not equal” because the two instances pointing two different locations, the ” ==” not checks the actual value, it checks the address of a location

HTML Comment Box is loading comments...