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 String object 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 Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

/* 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 x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

Also recommended reading:

  • Object.hashCode()
  • Effective Java (Bloch)
Answer from ppeterka on Stack Overflow
Top answer
1 of 7
20

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 String object 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 Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

/* 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 x and y, x.equals(y) should return true if and only if y.equals(x) returns true.
  • It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.
  • It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified.
  • For any non-null reference value x, x.equals(null) should return false.

Also recommended reading:

  • Object.hashCode()
  • Effective Java (Bloch)
2 of 7
9

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.

🌐
TutorialsPoint
tutorialspoint.com › explain-the-equals-method-of-the-object-string-and-stringbuffer-classes
Explain the equals() method of the Object, String and, StringBuffer classes.
But, unlike the Sting class the StringBuffer does not override the equals() method. Its functionality is same as in the Object class. Therefore, to get true you need to compare references pointing to the same value using the equal method. ... import java.util.Scanner; public class StringEquals ...
🌐
Baeldung
baeldung.com › home › java › java string › comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - On the other hand, the second assertion is false because string1 is created with a literal and string3 is created using the new operator – therefore they reference different objects. The String class overrides the equals() inherited from Object.
🌐
Coderanch
coderanch.com › t › 377876 › java › Object-equals-String-equals
Object.equals() vs String.equals() (Java in General forum at Coderanch)
In it you'll find that Object's equals method is defined as: And String's equals method is defined as: As the API states: The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.
🌐
GeeksforGeeks
geeksforgeeks.org › java › difference-between-and-equals-method-in-java
Difference Between == Operator and equals() Method in Java - GeeksforGeeks
January 4, 2025 - The main difference is that string equals() method compares the content equality of two strings while the == operator compares the reference or memory location of objects in a heap, whether they point to the same location or not.
🌐
Reddit
reddit.com › r/learnjava › == vs. .equals()??
r/learnjava on Reddit: == vs. .equals()??
July 3, 2020 -

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?

🌐
Knowledgewalls
knowledgewalls.com › johnpeter › books › one-day-one-thing-to-know › difference-between-string-equals-and-object-equals-in-java
Difference between string equals and object equals in JAVA?
Everyday one topic to go as master in Future. Book contains technical topics of computer software development. Such as MySQL, Core Java, HTML, CSS and JQuery and More.
🌐
Coderanch
coderanch.com › t › 410559 › java › Difference-Object-equals-String-equals
Difference between Object's equals() and String's equals() method ? (Beginning Java forum at Coderanch)
It will match based on the equals() method defines in the Object class. If you were expecting it to work based on the value this would be a misreading of the JavaDocs on your part. It will definitely break if you use StringBuffer as key because the equal method is not implemented in the class it uses Object class equal method.
Find elsewhere
🌐
W3Schools
w3schools.com › java › ref_string_equals.asp
Java String equals() Method
Operators Arithmetic Assignment Comparison Logical Precedence Code Challenge Java Strings
🌐
Blogger
javadiscover.blogspot.com › 2013 › 06 › difference-between-object-class-equals.html
Difference between Object class equals() and String class equals() - Java Discover
String Class: Basically equals() method in String class is overridden from Object class and used to compare whether some other Object is "equal to" this one, along with also Objects will be typecast to String and each character wise comparison ...
🌐
Reddit
reddit.com › r/learnjava › why to never use == with strings and instead use .equals()
r/learnjava on Reddit: Why to never use == with Strings and instead use .equals()
August 8, 2020 -

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 ?

🌐
Medium
medium.com › @AlexanderObregon › javas-objects-equals-method-explained-3a84c963edfa
Java’s Objects.equals() Method Explained | Medium
5 days ago - When it comes to comparing objects in Java, inconsistent handling of null values can lead to subtle bugs and unexpected behavior. The Objects.equals() method provides a consistent way to handle null values across your codebase. Whether you are comparing two strings, integers, or custom objects, Objects.equals() treats null values uniformly:
🌐
Scaler
scaler.com › home › topics › difference between comparing string using == and .equals() method in java
Difference between Comparing String Using == and .equals() Method in Java - Scaler Topics
June 2, 2024 - The equals() method in Java compares two objects for equality. It is defined in the Object class in Java. The equals() method compares characters by characters and matches the same sequence present or not in both objects.
🌐
Reddit
reddit.com › r/learnjava › confused on how equals() method works for objects and strings.
r/learnjava on Reddit: Confused on how equals() method works for objects and strings.
November 17, 2018 -

//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?

Top answer
1 of 4
12
The default implementation of equals does an object comparison, so your cir1.equals... is checking to see if they're the same (not just the same values). String, for instance, overrides the default equals method to check against the value not the object itself. You can override the equals method on your circle object to compare based on value (radius). More info
2 of 4
3
First of all, the objects aren't "the same" (which is why the default equals method returns false). They live in different places in memory so they the computer treats them as different objects. However, they are "equal." If you want the equals method to check for that equality then you have to implement it yourself. Here is some very bad code that isn't going to compile but maybe it's demonstrative anyway: public class Circle { private double radius; public Circle(double aRadius) { radius = aRadius; } public boolean equals(Circle c) { return this.radius == c.radius; } } The idea is that you have to tell the compiler what it should mean for two circles to be equal. In this case, you want to check that the radii are equal. That code is bad for several reasons, though. First, the equals method must take an Object as its argument (because you're overriding another method). Second, c.radius isn't going to work because radius is private (or at least it should be). Third, it is bad practice to check equality of doubles (more on this in a bit). Here is better code: public class Circle { private double radius; public Circle(double aRadius) { radius = aRadius; } public boolean getRadius() { return radius; } public boolean equals(Object o) { // this checks if this object and o are *actually* the same. if (o == this) { return true; } // Here we return false if o isn't actually a Circle object. if (!(o instanceof Circle)) { return false; } // If the code gets to this point we can safely assume that o is actually // a circle and we can do the radius check. Circle c = (Circle) o; return radius == c.getRadius(); } } The code above should do what you're describing but I still didn't address the "it is bad practice to check equality of doubles" issue. The problem is that the line return radius == c.getRadius(); isn't really going to work how you think. There is a lot of rounding involved in floating point computations and sometimes numbers that you think should be equal aren't going to be equal. There are several ways to handle this but the general idea is that you should invent some kind of "tolerance" where doubles that are within the tolerance of each other are considered equal. Something like this: Circle c = (Circle) o; double difference = radius - c.getRadius(); return (difference < 0.000000000001) && (difference > -0.000000000001); This code checks that the difference between radius and c.getRadius() is between 0.000000000001 and -0.000000000001. This still isn't the best; you shouldn't use a magic number like 0.000000000001 (instead there should be a global TOLERANCE variable) and there are already methods in the world to handle the comparison of doubles so it's probably better to use one of those but this isn't a thread about comparing doubles so I won't get into it any further.
🌐
Reddit
reddit.com › r/learnjava › can i use == in java for strings
r/learnjava on Reddit: Can I use == in Java for strings
October 8, 2024 -

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

Top answer
1 of 16
611

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.

2 of 16
593

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.

🌐
Java67
java67.com › 2012 › 11 › difference-between-operator-and-equals-method-in.html
Difference between == and equals() method in Java? String Example | Java67
For example java.lang.String class overrides the equals() and hashcode method and in the overridden method, it will check that two string contains same value or character if yes then they are equals otherwise not equal. Now what you know what is equals method, how it works and What is equality operator (==), and How it compares objects, it's time to compare them.
🌐
CodeGym
codegym.cc › java blog › java objects › java compare strings
Compare String and Equals comparisons in Java
April 2, 2025 - The keyword "this" refers to the object currently being used so when you call this equals method you would do something like this: man2.equals(man1); This is what the compiler does after calling that method: public boolean equals(Man man){ return man2.dnaCode == man1.dnaCode; } So basically "this" is referring to man2 because that is the object calling the method and man1 is the parameter. ... This was enlightening and visually easy to comprehend. ... Well, for me it was very interesting. I finished another Java course but the explanation here is much better. ... I liked this lesson! It's explain more things that I didn't understand. ... Crystal clear ! Thanks ! First time I've heard about this "String pool".