Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 10 of 10

Thread: Difference between == and equals.

  1. #1
    Member goldest's Avatar
    Join Date
    Oct 2009
    Location
    Pune, India
    Posts
    63
    Thanks
    1
    Thanked 12 Times in 10 Posts

    Unhappy Difference between == and equals.

    Hi guys,

    Here is my sample code,

    public class EqualsCheck {
     
    	public static void main(String[] args) {
    		EqualsCheck eq = new EqualsCheck();
    		eq.checkBytes();
    	}
     
    	public void checkBytes() {
    		Byte myByte = new Byte("111");
     
    		if (myByte.toString() == myByte.toString()) {
    			System.out.println("== is True");
    		} else {
    			System.out.println("== is False");
    		}
     
    		if (myByte.toString().equals(myByte.toString())) {
    			System.out.println("equals is True");
    		} else {
    			System.out.println("equals is False");
    		}
    	}
    }

    When I run it, I get the following output,
    == is False
    equals is True

    I am confused, because myByte.toString() always gives back the String value "111". Then how come == returns false and equals returns true.

    I know that == checks the references and equals checks the actual objects, but where are those references that == checks which are not the same.

    Can someone please clarify this for me?

    Thanks in advance!
    Goldest
    Java Is A Funny Language... Really!

    Sun: Java Coding Conventions

    Click on THANKS if you like the solution provided.
    Click on Star if you are really impressed with the solution.


  2. #2
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Difference between == and equals.

    What do you mean by "where are those references"? Where in terms of what?

    Like you said, when dealing with Objects, == compares the instances, not the content. Calling toString() twice apparently creates two different String instances. Therefore, comparing them with == returns false. However, since they contain the same information (as checked by the equals method), equals() returns true.

  3. #3
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: Difference between == and equals.

    Read this, it is a common question: http://www.javaprogrammingforums.com...html#post18725
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  4. The Following User Says Thank You to aussiemcgr For This Useful Post:

    JavaPF (December 17th, 2010)

  5. #4
    Junior Member
    Join Date
    Dec 2010
    Posts
    7
    My Mood
    Cool
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Difference between == and equals.

    thanks for the reply..but Can you please tell me when to use == and and in what cases i have to go for equals?

  6. #5
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Difference between == and equals.

    Quote Originally Posted by rafishaik999 View Post
    thanks for the reply..but Can you please tell me when to use == and and in what cases i have to go for equals?
    That depends on your requirements. Use == when you want to compare instances. Use the equals() method when you want to compare the semantics of those instances.

  7. #6
    Super Moderator helloworld922's Avatar
    Join Date
    Jun 2009
    Posts
    2,895
    Thanks
    23
    Thanked 619 Times in 561 Posts
    Blog Entries
    18

    Default Re: Difference between == and equals.

    == is also used for comparing the values of primitives. The equals method cannot be used directly on primitives (They must be wrapped).

    int a = 5;
    int b = 5;
    if(a == b)
    {
        System.out.println("a and b exist in different locations in memory, but are ==");
    }

    The same thing may or may not apply with primitives that have been wrapped (assume it's not).
    Integer a = new Integer(5);
    Integer b = new Integer(5);
    if(a == b)
    {
        System.out.println("a and b are the same integer object. In this case this is not true.");
    }
    if(a.equals(b))
    {
        System.out.println("a and b contain the same value.");
    }

    For strings, it's often difficult to determine if two string are the same object in memory, so it's almost always a good idea to compare strings using equals().

  8. #7
    Junior Member
    Join Date
    Dec 2010
    Posts
    7
    My Mood
    Cool
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Difference between == and equals.

    this is really helpful information. thanxalot for explaining with example..

  9. #8
    Member goldest's Avatar
    Join Date
    Oct 2009
    Location
    Pune, India
    Posts
    63
    Thanks
    1
    Thanked 12 Times in 10 Posts

    Red face Re: Difference between == and equals.

    Thanks for the replies guys.

    What I understood is that, when we want to compare the references of primitives, we should use == operator. If both the references have the same value stored, then they will return true, else false. Like,


    int x = 5;
    int y = 5;
    System.out.println("x == y : "+(x == y));
    which returns
    x == y : true

    Now when we want to compare the contents of objects, like the Wrapper primitives, Strings or any other objects, we should use the equals() method. Like,
    String l = new String("Goldest");
    String m = new String("Goldest");
    System.out.println("l == m : " +(l == m));
    System.out.println("l equals m : " +l.equals(m));
    which returns
    l == m : false
    l equals m : true
    Because there are 2 new String objects created on heap and both l and m are referring to them individually. So there reference comparison returns false. But as they both contains same value, "Goldest", there equals returns true.

    But when we come to Strings with plain values, like,
    String a = "Goldest";
    String b = "Goldest";
    System.out.println("a == b: "+(a == b));
    System.out.println("a equals b : " +a.equals(b));
    which returns
    a == b: true
    a equals b : true
    Here, as Strings are IMMUTABLE, when we create same value strings only one gets created on the heap. Whenever we create new String objects to refer to value "Goldest" all of them refers to the ONLY String "Goldest" present on the heap. And thats why both a and b returns true when we apply the == test on them. And the equals test will anyways give true as the contents are same.

    And in my original example, when myByte.toString() gets compared to myByte.toString(), what happens internally is that 2 different String objects get created by JVM to store the String values that are returned by the toString() method. And later, both of them are compared with each other by using the == operator. Like,
    String x = myByte.toString();
    String y = myByte.toString();
    System.out.println("x == y: " +(x == y));
    which returns
    x == y: false
    And because of that ultimately "== is False" is printed.

    Please let me know whether I have grasped it correctly or not.

    Thanks in advance,
    Goldest
    Java Is A Funny Language... Really!

    Sun: Java Coding Conventions

    Click on THANKS if you like the solution provided.
    Click on Star if you are really impressed with the solution.

  10. #9
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: Difference between == and equals.

    Seems like you got it. To really drive the point home, try doing something like this:

    String x = new String("Goldest");
    String y = new String("Goldest");
    System.out.println("x == y : " + (x == y));
    System.out.println("x.equals(y) : " + (x.equals(y)));

  11. #10
    Member goldest's Avatar
    Join Date
    Oct 2009
    Location
    Pune, India
    Posts
    63
    Thanks
    1
    Thanked 12 Times in 10 Posts

    Default Re: Difference between == and equals.

    Ohh yeah!

    Thanks a lot for all your help and support.

    Goldest
    Java Is A Funny Language... Really!

    Sun: Java Coding Conventions

    Click on THANKS if you like the solution provided.
    Click on Star if you are really impressed with the solution.

Similar Threads

  1. Replies: 1
    Last Post: August 13th, 2010, 06:58 AM
  2. [SOLVED] difference between fileReader and bufferReader
    By shadihrr in forum Java Theory & Questions
    Replies: 6
    Last Post: June 8th, 2010, 01:26 AM
  3. Equals Method
    By Sninald in forum What's Wrong With My Code?
    Replies: 1
    Last Post: February 18th, 2010, 03:06 AM
  4. Arrays.equals not returning correct answer.
    By Anyone in forum Collections and Generics
    Replies: 2
    Last Post: February 11th, 2010, 10:12 AM
  5. Need to know this difference
    By arvind in forum Java Theory & Questions
    Replies: 2
    Last Post: January 19th, 2010, 06:24 AM