Do you really know the difference between == and .equals?

the difference between == and .equals is commonly asked in tests and interviews. heres a brife explanation of the differences between them.

A common misunderstanding is that, == compares the value for primitive types and the address for the reference types, but equals only compare the value. But thats not the case with java, as for why its incorrect, just keep reading, and you’ll find your answer.

What does == do?

== acts differently on different types, heres an example

On primitive types, == would always work properly

1
2
3
int nice = 69;
int veryNice = 69;
System.out.println(nice == veryNice); //true

On reference types, it acts a bit differently, it would compare the address of the object instead of the value, therefore comparing two objects with the same value would return false.

1
2
3
String nice = "NICE";
String veryNice = "NICE";
System.out.println(nice == veryNice); //true

Wait what? Shouldn’t it return false since they are both reference types?

Well, they are indeed reference types, but when you declare the strings without using new, you’ll get a reference to a single String instance. This is because string literals in java will be interned if they are the same, which means that both variables have reference to the same thing.

Now Let’s try it with the new operator

1
2
3
String nice = new String("NICE");
String veryNice = new String("NICE");
System.out.println(nice == veryNice); //false

Ah yes, it’s finally false.

Now you can see how == returns false, even though they contain the same value, they are still different objects, which have a different reference. So, when == tries to compare them, it would return false because they have different references.

not finished smh


all articles in this blog are licensed under CC BY-SA 4.0