Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling equals(""); by itself compiles and runs

Tags:

java

equals

I've noticed that calling equals(""); in a method of a class is not generating any error within Eclipse. I've never seen .equals called without something like string1.equals(string2);.

package voodoo;

public class Equals {

    public void method(){
        equals("");
    }

}

What's going on here and when would calling equals() by itself ever be used?

If I put that into a JUnit to test, it runs and passes.

like image 987
Dumpcats Avatar asked Sep 09 '15 18:09

Dumpcats


People also ask

What is the purpose of the equals () method?

Definition and Usage. The equals() method compares two strings, and returns true if the strings are equal, and false if not.

Which class contains the equals () method being called here is it calling itself?

The equals() public method at Object class. All class by default a direct/indirect child class of Object class. Your Equals class doesn't inherit any class explicitly. So it is an direct subclass of Object .

Is equals () a static method?

The equals() method is a static method of the Objects class that accepts two objects and checks if the objects are equal. If both the objects point to null , then equals() returns true .

How do you call equals method in Java?

In Java terms, they are equal, which is checked with equals : String some = "some string"; String other = "some string"; boolean equal = some. equals(other); Here, equals is true .


1 Answers

equals that you are calling is Object's equals method, which can be called on this reference without specifying it explicitly. In other words, your call is equivalent to

this.equals("");

This is perfectly valid, although a well-behaved implementation must always return false. Note that the return value is ignored, which is legal as well.

You can see what's going on by overriding equals with something that prints a message, as a matter of an experiment:

public class Equals {

    public void method(){
        equals("");
    }
    @Override
    public boolean equals(Object other) {
        System.out.println("I am being compared to '"+other+"'");
        return super.equals(other);
    }
}
like image 70
Sergey Kalinichenko Avatar answered Sep 22 '22 15:09

Sergey Kalinichenko