How does .equals Java String Class method work?

荒凉一梦 提交于 2019-12-11 09:46:28

问题


In java there is a string class method that works as seen bellow. But I wonder how is it that we are able to call the method on a random variable of type string?

String word = "hello"
word.equals("hello");

output is true


回答1:


The equals() method is used to verify if the state of the instances of two Java classes is the same. Because equals() is from the Object class, every Java class inherits it. But the equals() method has to be overridden to make it work properly. Of course, String overrides equals().

Take a look:

public boolean equals(Object anObject) {
    if (this == anObject) {
        return true;
    }

    if (anObject instanceof String) {
        String aString = (String)anObject;
        if (coder() == aString.coder()) {
          return isLatin1() ? StringLatin1.equals(value, aString.value)
            : StringUTF16.equals(value, aString.value);
        }
    }

    return false;
}

As you can see, the state of the String class value has to be equals() and not the object reference. It doesn’t matter if the object reference is different; the state of the String will be compared

I have taken it from here. Better if you have an idea about String pool also. So please refer the link




回答2:


If you are comparing String with primitives like int,long. The answer is String is not a primitive. It is a class. There are several ways to create an object from this class, like

String word=new String("hello");
String word="hello"; //special case for String class

now word becomes an object and you can call the method equals(because every object you create is inherited from java.lang.Object) class.

If you look at primitives like int. you cannot do something like below, beacause number is not an object.

int number=12; 
number.equals(12)



回答3:


String class (String in Java is Object) inherited equals method from Object and override it as is correctly mentioned in answers by Sand and Armine.

We can call methods on String (even on constant String, statement: "Hello World".length() returns 11) because String is an Object and not a primitive type. Primitive types are byte, short, int,... You could read more about them here

Nice reading about differences between primitives types and Objects: Difference between Primitive and Reference variable in Java




回答4:


equals method compares the string on which the method is called with the string which is passed as a parameter.

Take a look at these links:

String Comparison

Equals on String

Overriding equals in String class



来源:https://stackoverflow.com/questions/53263058/how-does-equals-java-string-class-method-work

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!