Results 1 to 5 of 5
  1. #1
    meenakshipuni is offline Member
    Join Date
    Oct 2011
    Posts
    5
    Rep Power
    0

    Default Difference between == and equals()

    Hi Every One,

    Can anyone explain me the difference between equality operator (==) and equals() method.

    I am jus trying the following code... please explain me.

    String s = new String("abc");
    String s1 = new String("abc");

    System.out.println("String Equals : "+s==s1); // It returns false
    System.out.println("String Equals Opr: "+s.equals(s1));//It return true.


    Thanks in advance

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,764
    Blog Entries
    7
    Rep Power
    21

    Default Re: Difference between == and equals()

    Suppose you and I are pointing to the same, say, television set; the == operator returns true because we're both pointing to one television set. Now, suppose we're both pointing to two different sets. The == operator will return false but the equals( ... ) method might return true if both television sets are the same brand, the same size etc.

    kind regards.

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    meenakshipuni is offline Member
    Join Date
    Oct 2011
    Posts
    5
    Rep Power
    0

    Default Re: Difference between == and equals()

    Thanks for ur valuable explanation...

  4. #4
    Join Date
    Nov 2011
    Posts
    28
    Rep Power
    0

    Default Re: Difference between == and equals()

    == for primitive type comparisons
    .equals() for object comparisons

  5. #5
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,800
    Rep Power
    7

    Default Re: Difference between == and equals()

    That is not 100% true. There are situations where you do want to use == to compare object references.

Similar Threads

  1. c always equals a*b
    By imorio in forum New To Java
    Replies: 3
    Last Post: 11-12-2010, 03:32 PM
  2. == and equals()
    By arefeh in forum New To Java
    Replies: 13
    Last Post: 01-05-2010, 05:56 PM
  3. == is same as .equals()??
    By DrMath in forum New To Java
    Replies: 1
    Last Post: 09-30-2009, 05:57 AM
  4. Replies: 0
    Last Post: 01-26-2008, 12:13 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •