Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 650
Lucas T Avatar asked Feb 19 '26 00:02

Lucas T


1 Answers

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.

like image 93
Óscar López Avatar answered Feb 21 '26 12:02

Óscar López



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!