Interview Questions

difference between == and equals method in java ?

24 Jul , 2015  

So here is the question “What is the difference between == and equals method in java ?” which you must have heard lots of time. Most of the time in Interviews. In this article I will discuss about it.
So what would be my answer if anyone ask me this question. My Answer would be, there is no difference in == and equals. I know this answer is not same as you have heard till now. Don’t worry i will prove my point.

                                                For Coffee Vendor Machine Program Click here

To understand the difference, You need to understand the question carefully. If I ask the difference between == and equals I am asking this in terms of Objects. But most of the time people relate this question to String Object only and give the answer accordingly.
Why == and equals are same ?
In Object class equals() method internally uses == operator only. Hence there is no difference between these two.
Implementation of equals() method in Object class

Output of above program would be
As you can see equals and == behave in the same way. But every time i ask this question to any one he/she use to give answer as true and false. Reason, why they are giving this answer is because they always think of this question in terms of String object.

What is Special about String Object ?

So what is special about String object. And why equals and == behave differently in case of String Object. The answer is String, Object Overrides equals () method of the Object class. And it provides different behavior that Object class.

As you can see, In String class equals method compares the value of each character in String and give the answer accordingly and it is not using == operator.

Equals method in String Object

Output of above programe would be

Reason for this answer is that, here == operator checks if reference for two objects are same or not? In given case(str & str1) it is different hence answer is false. And equals method checks value of each character in string. As it is same(Hello) in both cases hence it returns true.
So now you know the difference between equals method and == operator. If tomorrow Interviewer asks you this question. First ask Interviewer in which term they are asking this question? (String or Object)

For fizz buzz program click here


4 Responses

  1. rakesh says:

    Thanks …this is very helpful answer for me…

  2. Amit says:

    Waiting for this question. Thanx . Upload Core java and framework related post

  3. Tom says:

    its nyc….bt i want core java related post…so plz upload

  4. satish says:

    gre8 sir

Leave a Reply

Your email address will not be published. Required fields are marked *