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.
== acts differently on different types, heres an example
On primitive types,
== would always work properly
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.
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
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