Site icon NgDeveloper

Difference between Equals() and ==

Difference between Equals() and ==:

Equals():
It compares the content of the object.

Example program:

[java]
package com.ngdeveloper.com;

public class Equals {

public static void main(String[] args) {
String s1 = "hello";
String s2 = new String("hello");
String s3 = s1;
String s4 = "Hello";

System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println(s4.hashCode());

System.out.println(s1.equals(s2));
System.out.println(s2.equals(s3));
System.out.println(s3.equals(s1));
System.out.println(s4.equals(s2));

}

}
[/java]

Output:

99162322
99162322
99162322
69609650
true
true
true
false

==:

It compares the object location in memory.

Example Program:

[java]
package com.ngdeveloper.com;

public class Equals {

public static void main(String[] args) {
String s1 = "hello";
String s2 = new String("hello");
String s3 = s1;
String s4 = "hello";

System.out.println((s1==s2));
System.out.println((s2==s3));
System.out.println((s3==s4));
System.out.println((s4==s1));

}

}
[/java]

Output:

false
false
true
true

Exit mobile version