Image Image Image Image Image Image Image Image Image Image

Mudassir Shahzad | April 26, 2019

Scroll to top


No Comments

The famous java == and .equals()

The famous java == and .equals()
Mudassir Shahzad

In Java, there is a difference between java == and equals() method to compare primitives (int, float etc), strings and objects. This is a short article just to clear the difference between the both.

You can tell the difference by just two lines:

== tests for reference equality.

.equals() tests for value equality.


Repeat with me,

== tests for reference equality.

.equals() tests for value equality.


Once more, with feeling

== tests for reference equality.

.equals() tests for value equality.


Here, remember that == first tests the datatype and then checks for reference equality.


Now, that we know the difference between the both, let’s try some code example because if you don’t code, no matter how many books you read or how many articles you go through, you will not know the difference.


So, come on, open up your java code editor and let’s try the examples given below:


According to Oracle String#intern

A pool of strings (String pool), initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, thisString object is added to the pool and a reference to this String object is returned.

In short, String#intern() is a function which checks for an already existing string in the string pool. If found, returns the reference, otherwise creates a new object and returns the reference.


Submit a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.