2

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?

Community
  • 1
  • 1
Lucas T
  • 3,011
  • 6
  • 29
  • 36
  • 4
    I am expecting over four answers – dragon66 May 10 '12 at 14:13
  • Check about string interning - http://en.wikipedia.org/wiki/String_intern_pool. The second conditional fails because the two string objects are not the same, therefor the references are not the same and == returns false. –  May 10 '12 at 14:14
  • http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.21 – hmjd May 10 '12 at 14:14
  • FYI, the link I posted above is part of the Java FAQ at the bottom of [that page](http://stackoverflow.com/tags/java/info). – assylias May 10 '12 at 14:14
  • 1
    @dragon66:ur desire fulfilled..more than four... – Shahzad Imam May 10 '12 at 14:17

3 Answers3

6

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.

Óscar López
  • 232,561
  • 37
  • 312
  • 386
3

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

Marcin
  • 48,559
  • 18
  • 128
  • 201
0

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.

FThompson
  • 28,352
  • 13
  • 60
  • 93