问题
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 String
s. ==
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