Possible Duplicate:
How do I compare strings in Java?
When I run the following code as “java XYZ BOY”
the output is “Invalid type”, how??
public class XYZ
{
public static void main(String args[])
{
if(args[0]=="BOY")
System.out.println("He is boy");
else if(args[0]=="Girl")
System.out.println("She is girl");
else
System.out.println("Invalid type");
}
}
However when I use args[0].equals("BOY"), it gives the desired output. I want to know why things go wrong here when I don’t use String.equals()?
The operator
==tests if two variables refer to the very same object which isn’t what you’re interested in. Instead you want to know if two String variables refer to String objects that hold the same characters in the same order and in the same case, which is whatequals(...)does, or regardless of case, which is whatequalsIgnoreCase(...)does.All classes get a default
equals(...)method from the ultimate parent class, Object, which if not overridden will do the very same thing as==, as per the API:Many classes have this method overridden to use their own test of equality that makes sense for the class. String is one such class. For more details on how String does this, please check out its API which states:
Having said all of this — voting to close this question as a duplicate.