Difference between Equals() and ==:
Equals():
It compares the content of the object.
Example program:
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)); } }
Output:
99162322
99162322
99162322
69609650
true
true
true
false
==:
It compares the object location in memory.
Example Program:
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)); } }
Output:
false
false
true
true
1,004 total views, 1 views today
Leave a Reply