Because equals() for String compares the content, not the object itself.
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a
Stringobject that represents the same sequence of characters as this object.
/* String.equals() */
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
(Link to the source of String.equals())
Versus the equals for Object:
The equals method for class
Objectimplements the most discriminating possible equivalence relation on objects; that is, for any non-null reference valuesxandy, this method returns true if and only ifxandyrefer to the same object (x == yhas the valuetrue).
/* Object.equals() */
public boolean equals(Object obj) {
return (this == obj);
}
(Link to the source of Object.equals())
Also, don't forget the contract of the equals() function:
The equals method implements an equivalence relation on non-null object references:
- It is reflexive: for any non-null reference value
x,x.equals(x)should return true.- It is symmetric: for any non-null reference values
xandy,x.equals(y)should return true if and only ify.equals(x)returns true.- It is transitive: for any non-null reference values
x,y, andz, ifx.equals(y)returnstrueandy.equals(z)returnstrue, thenx.equals(z)should returntrue.- It is consistent: for any non-null reference values
xandy, multiple invocations ofx.equals(y)consistently returntrueor consistently returnfalse, provided no information used in equals comparisons on the objects is modified.- For any non-null reference value
x,x.equals(null)should returnfalse.
Also recommended reading:
- Object.hashCode()
- Effective Java (Bloch)
Because equals() for String compares the content, not the object itself.
public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not null and is a
Stringobject that represents the same sequence of characters as this object.
/* String.equals() */
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = count;
if (n == anotherString.count) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}
}
return false;
}
(Link to the source of String.equals())
Versus the equals for Object:
The equals method for class
Objectimplements the most discriminating possible equivalence relation on objects; that is, for any non-null reference valuesxandy, this method returns true if and only ifxandyrefer to the same object (x == yhas the valuetrue).
/* Object.equals() */
public boolean equals(Object obj) {
return (this == obj);
}
(Link to the source of Object.equals())
Also, don't forget the contract of the equals() function:
The equals method implements an equivalence relation on non-null object references:
- It is reflexive: for any non-null reference value
x,x.equals(x)should return true.- It is symmetric: for any non-null reference values
xandy,x.equals(y)should return true if and only ify.equals(x)returns true.- It is transitive: for any non-null reference values
x,y, andz, ifx.equals(y)returnstrueandy.equals(z)returnstrue, thenx.equals(z)should returntrue.- It is consistent: for any non-null reference values
xandy, multiple invocations ofx.equals(y)consistently returntrueor consistently returnfalse, provided no information used in equals comparisons on the objects is modified.- For any non-null reference value
x,x.equals(null)should returnfalse.
Also recommended reading:
- Object.hashCode()
- Effective Java (Bloch)
equals for Object compares memory references.
That is why it is false since they are different Objects
equals for String is overridden to compare based on characters.
You have 2 empty String objects that is why equals returns true.
Videos
I'm on MOOC.fi and I'm a little confused on why you can't use .equals() when comparing two objects. And on part 5_12.Song programming exercise, I'm confused on why the parameter takes an Object parameter instead of a "Song" type, and then why do we have to typecast the object to compare it?
In class we were discussing this and basically I understood == tests the EXACT same thing... since Strings are each their own object, we need a special method to check for if they are actually the same words. Furthermore, == tests the address I believe?
Here's the confusing part for me... Java has optimized == so SOMETIMES "hello" == "hello" will return true even if they are two unique Strings... but "hell" += "o" == "hello" returns false. Why ?
You need to do some reading up on the String Constant Pool and the difference between Stack and Heap memory(Strings and their construction are usually discussed in detail here for reasons that will become clear).
Sorry for the short answer but it's a very dense topic that is usually covered across multiple chapters in books. This will get you what you need though.
== operator checks the equality of the object identity, i.e. 2 objects == each other if they are indistinguishable from each other. Currently, in Java, each object has its own unique identity, but not a unique address. As a result, understanding that == tests for address equality is not correct.
Java does not optimised == so that "hello" == "hello", the thing got optimised here is how Java stores the String object, which leads to 2 string literal declarations with the same contents are detected and assigned to a single String object.
//Suppose I have another class with a default constructor method
public Circle(double r)
{
radius =r;
}
//and in my main class I have the codes
Circle cir1= new Circle(5.1);
Circle cir2= new Circle(5.1);
System.out.println(cir1.equals(cir2));
// Why would the output be false? If i use the equals() method to compare the content of two strings, then why wouldnt it work the same way when comparing the contents with two different objects? How is the output false if the arguments are the same?
My CS teacher told me that you have to use .equals() when comparing strings instead of == but today I tried using == and it worked. Was this supposed to happen or was it like a new update?
public class Main{
public static void main(String[] args) {
String name = "jarod";
if(name == "jarod"){
System.out.println("ELLO JAROD");
}else{
System.out.print("NO");
}
}
}For this bit of code the output was ello Jarod and if I put in something else for the string variable it gave me no
Use the string.equals(Object other) function to compare strings, not the == operator.
The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.
if (usuario.equals(datos[0])) {
...
}
NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.
Meet Jorman
Jorman is a successful businessman and has 2 houses.

But others don't know that.
Is it the same Jorman?
When you ask neighbours from either Madison or Burke streets, this is the only thing they can say:

Using the residence alone, it's tough to confirm that it's the same Jorman. Since they're 2 different addresses, it's just natural to assume that those are 2 different persons.
That's how the operator == behaves. So it will say that datos[0]==usuario is false, because it only compares the addresses.
An Investigator to the Rescue
What if we sent an investigator? We know that it's the same Jorman, but we need to prove it. Our detective will look closely at all physical aspects. With thorough inquiry, the agent will be able to conclude whether it's the same person or not. Let's see it happen in Java terms.
Here's the source code of String's equals() method:

It compares the Strings character by character, in order to come to a conclusion that they are indeed equal.
That's how the String equals method behaves. So datos[0].equals(usuario) will return true, because it performs a logical comparison.