The class Object defines an equal() method to compare objects.
Specify the advantages and disadvantages of using this method
and suggest an alternative for equality.
Illustrate with code examples.
(Please elaborate on the advantages and disadvantages; also please include your sources and references) Thanks a lot!
Consider this code:
String x = "Hello World";
String y = "Hello " + "World";
if (x == y)
System.out.println("The strings are ==");
if (x.equals(y))
System.out.println("The strings are equal");
The first will not print, but the second one will. This is because
the two Strings are not the same object, even though they contain
the same content.
The .equals() method, on the other hand, is smart enough to check
the contents. It sees that both contain "Hello World" so it returns
true.
If you did this:
String x = "Hello World";
String y = x;
if (x == y)
System.out.println("The strings are ==");
then it would print, because x and y would actually be the same
object.
Here's the details as to why this is.
Deep down, if you have a primitive variable (like int), the value
is stored in the variable. If you have int j = 8; then 8 is stored
in the j variable. And if you then have int k = 8; then k will also
have 8 stored in it. So if you use == on them, they will show as
equal.
But if you have an object (like a String) then what is actually
stored in the variable is a memory location which contains the rest
of the object. So if you have String x = "Hello World"; then x does
not *really* contain "Hello World" - it contains something like
0x13F70000, which is a memory location which then contains "Hello
World". Then if you have String y = "Hello " + "World"; it's going
to create a new memory location and also put "Hello World" in it.
But now y is maybe 0x13F70040. It contains a different value than
the x variable, so == will see them as not equal.
(And if you're wondering "well, why doesn't Java just share that
memory location so both variables can use it" - sometimes it does,
for Strings. That's known as string interning. So if you have
String x = "Hello World"; and String y = "Hello World"; then the
compiler might recognize that they are the same and cause them to
use the same memory location, and == might return true.)
Alternative:
Using compare() method
In Java for locale specific comparison, one should use Collator class which is in java.text package. The one most important feature of Collator class is the ability to define our own custom comparison rules.
References- https://www.geeksforgeeks.org/java-equals-compareto-equalsignorecase-and-compare/
Get Answers For Free
Most questions answered within 1 hours.