views:

876

answers:

12

String parts is String[6]:

[231, CA-California, Sacramento-155328, aleee, Customer Service Clerk, Alegra Keith.doc.txt]

But when I compare parts[0] with "231":

"231" == parts[0]

the above result is false,

I'm confused, so could anybody tell me why?

+8  A: 

== in Java compares the address of the objects (strings in this case).

What you want is parts[0].equals("231")

David Johnstone
+11  A: 

The == operator compares the object references, not the value of the Strings.

To compare the values of Strings, use the String.equals method:

"231".equals(parts[0]);

This is true with any other object in Java -- when comparing values, always use the equals method rather than using the == operator.

The equals method is part of Object, and should be overridden by classes which will be compared in one way or another.

coobird
+4  A: 

Use equals method: parts[0].equals("231"). == operator compares object references.

tputkonen
+5  A: 

If the strings are not interned, then == checks reference identity. Use:

 "231".equals(parts[0]);

instead.

Yishai
+1 for mentioning that string literals return true when compared to each other. A student of mine would not believe me that == does not check the actual contents of the string as every example that he gave me used string literals and returned true.
Brandon Bodnár
+3  A: 

"==" compares object references, in your case "231" is a different object than parts[0].

You want to use String.equals.

parts[0].equals("231")
basszero
It's often a good idea to use "foo".equals(bar) instead of bar.equals("foo"). The first piece of code will work regardless of whether or not bar is null. The second piece of code will throw a NullPointerException.
William Brendel
+1  A: 

The answer is very simple: when you compare strings through == operator, you actually compare if two different variables refer to a single String object. And they don't, the string in the array and newly created "231" are different String objects with the same contents.

The right thing to do is to use the folllowing expression: "231".equals(parts[0]) or "231".equalsIgnoreCase(parts[0]). This will give you what you need and return true if these String objects contain the same values.

Malcolm
+1  A: 

Use the equals method to compare objects:

String[] test = {"231", "CA-California", "Sacramento-155328", "aleee",
                 "Customer Service Clerk", "Alegra Keith.doc.txt"};

System.out.println("231".equals(test[0]));

The comparison '==' compares references, not values.

Don Branson
A: 

I thought it might be helpful to express the answer in a test case:

public class String231Test extends TestCase {
    private String a;
    private String b;

    protected void setUp() throws Exception {
     a = "231";
     StringBuffer sb = new StringBuffer();
     sb.append("231");
     b = sb.toString();
    }

    public void testEquals() throws Exception {
     assertTrue(a.equals(b));
    }

    public void testIdentity() throws Exception {
     assertFalse(a == b);
    }
}
Carl Manaster
A: 

The following prints out "true";

     String s = "231";
 if(s == "231")
 {
  System.out.println("true");
 }
 else
 {
  System.out.println("false");
 }

This is because Strings are not mutable and java will try and save as much space as possible, so it points both to the same memory reference.

However, the following prints out "false":

     String s = new String("231");
 if(s == "231")
 {
  System.out.println("true");
 }
 else
 {
  System.out.println("false");
 }

"new" will force it to store the string in a new memory location.

By the way, you should ALWAYS use .equals() to compare strings (for cases just like this one)

Jesse
Why was this downvoted?
Jesse
Because that's not exactly what the author asked about, I assume.
Malcolm
A: 

As many others have already explained, you try to compare with equality operator, but then it would relies on Object.equals() instead of String.equals().

So you can do the job by explicitly calling String.equals(), but instead of writing

parts[0].equals("blahblah")

I would prefer such :

"blahblah".equals(parts[0])

As it avoids testing potential nullity of parts[0] (but be careful that parts variable itself could be null...)

Another way is using String.intern() :

if (parts[0].intern() == "blahblah") ...

See http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#intern() for more info on that.

zim2001
A: 

Here's really nice example. The '==' operator with string can be really tricky in Java.

class Foo {
    public static void main(String[] args) {
        String a = "hello";
        String b = "hello";
        String c = "h";
        c = c + "ello";

        String operator = null;

        if(a == b) {
            operator = " == ";
        } else {
            operator = " != ";
        }

        System.out.println(a + operator + b);

        if(a == c) {
            operator = " == ";
        } else {
            operator = " != ";
        }

        System.out.println(a + operator + c);

        if(a == "hello") {
            operator = " == ";
        } else {
            operator = " != ";
        }

        System.out.println(a + operator + "hello");

        if(c == "hello") {
            operator = " == ";
        } else {
            operator = " != ";
        }

        System.out.println(c + operator + "hello");
    }
}

Which will produce following output:

hello == hello
hello != hello
hello == hello
hello != hello
picca
A: 

You may also use compareTo(String) method:

String str = "test";

if( str.compareTo("test") == 0)
   //the argument string is equal to str;
else
   //the argument string is not equal to str;
JCasso
It's only a bit more expensive than `equals()` and not really to be used to compare strings on **equality**.
BalusC
Talking about performance, we have to mention hashCode and intern... Also there are some exceptions that compareTo runs faster. If two strings has the same reference or they have different length equals give better performance however reference check and length check is redundant sometimes such as comparing substrings for equality. compereTo method gives a better performance if two strings does not have same reference (user input, substring) and having same length.
JCasso