equals() vs contentEquals() vs ==

Why equals method is used?

To compare two string contents [One string can be in stack memory and other can be in Heap memory, still it compares the contents of the strings]

String s1 = “abc”;

String s2 =  “abc”;

String s3 = new String (“abc”);

System.out.println(s1.equals(s2));  // o/p: True  [hashcodes are same in this case]

System.out.println(s1.equals(s3));   // o/p: True [hashcodes are different in this case]

Why ‘==’ is used?

It is an operator which compares the Hashcodes (not the content present inside them).

String s1 = “abc”;

String s2 =  “abc”;

String s3 = new String (“abc”);

System.out.println(s1==s2);  // o/p: True  [hashcodes are same in this case]

System.out.println(s1==s3);   // o/p: False [hashcodes are different in this case]

Why contentEquals is used?

It is used to compare the String object with StringBuffer/StringBuilder/ Char Array objects.

Note:

  • You can’t compare String object with StringBuffer object using equals method.
  • You can compare String object with another String object using equals and contentEquals methods. [both are same, but equals is specific to compare strings only]

 

String s1 =”abc”;

String s2 =new StringBuilder(“abc”);

System.out.println(s1.contentEquals(s2)); // o/p: true [hashcodes are different in this case]

 

Advertisements

2 thoughts on “equals() vs contentEquals() vs ==

  1. Santhosh May 26, 2017 / 5:09 pm

    Thanks

    In 2nd case and 1st case there is no difference

    s1 is equal to s3 I think you may need to use StringBuilder or StringBuffer

  2. Ravi Teja May 26, 2017 / 5:49 pm

    I’ve updated the code now. thanks for your response 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s