Java Core – The different between equals() and Operator “==”?

In the tutorial, JavaSampleApproach will introduce you the difference between equals() and operator “==” in Java.

I. Introduction

For comparing between 2 Objects in Java, we can use locations in memory of Objects or states of them.
Note: the state of a Java Object is defined by members’ value of the Object.

II. Java Operator “==”

– In Java, Operator “==” is used to compare 2 Ojects by memory addresses of them.
Sample:

Output:

Why?
s1 == s2 is false because s1 and s2 do not have the same memory address.
s1 == s3 is true because s1 and s3 have the same memory address.

Question:

With the above segment code, what is a result?
Answer: s1 == s3 is false, Because of s3 = s3 + “123”, then s3 points to another memory address.

III. Java equals() method

In Java, equals() methods is defined in the Object class. And by default, equals() likes “==” operator, it will check memory addresses of objects for comparing.
Best practice: should overide equals() by compare members’ value of Objects instead memory addresses.

Sample:

Question: What is output of above segment code?
Answer: s1 == s2 is true
Why? Because String class overrides the equals() method, it checks only values of string instead of memory addresses for comparing.

IV. Full Sourcecode

Output:


Related Posts



Got Something To Say:

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

*