== vs .equals - why different behaviour? [duplicate]

巧了我就是萌 提交于 2019-12-12 19:44:30

问题


Possible Duplicate:
How do I compare strings in Java?

I'm sorry for this rather simple question. I have this very simple java program:

public class ArgIt {
    public static void main(String[] args){
            if(args[0].equals("x")) System.out.print("x");
            if(args[0] == "x") System.out.println("x2 ");
    }
}

If I call the program >java ArgIt x it only prints a single x. Why will the program not acknowledge the == on the string when in any other circumstances it does?


回答1:


In Java, you must use equals() for comparing equality between Strings. == tests for identity, a different concept.

Two objects can be equal but not identical; on the other hand if two objects are identical it's implied that they're equal.

Two objects are identical if they physically point to the same address in memory, whereas two objects are equal if they have the same value, as defined by the programmer in the equals() method. In general, you're more interested in finding out if two objects are equal.




回答2:


== tests for pointer equality;.equals exists to test for value equality.




回答3:


In Java, comparing with the == operator checks for identity equality, as in the references (in the case of objects) point to the same memory location. Because of this, only primitives should be compared using the == operator, as primitives (int, long, boolean, etc) are stored by value rather than by reference.

In short, use the equals method to compare objects, and the == operator to compare primitives.



来源:https://stackoverflow.com/questions/10535804/vs-equals-why-different-behaviour

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