views:

122

answers:

4

I'm wondering why the following code doesn't work:

String test = new String(new byte[] {92, 92, 92, 92, 92});
System.out.println(test);
String compare = "\\\\\\\\\\";
System.out.println(compare);
if (test == compare) {
System.out.println("Yes!");
}

The output is:

\\\\\
\\\\\

Where is a data type conversion happening that I'm not understanding?

Edit: /fail :(

+9  A: 

Strings are compared with .equals(), not with ==

The reason is that with references (as string variables are), == just checks equality in memory location, not in content.

The literal \\\ existed in one place in memory. the other one is created somewhere else where you build the string. They're not in the same location, so they don't return true when you do ==

You should do

if(test.equals(compare))
Uri
That is correct. You are doing a reference comarison instead of a value comparision. They are not the same object, but they are equivalent. Use Equals and is should work.
CaptnCraig
+2  A: 

You are using identity comparison, rather than string comparison.

Try test.equals(compare). Then try test.intern() == compare. Both should work. The intern method is the only reliable way to perform object identity comparisons on String objects.

erickson
Just to raise a point about this answer, the "intern()" one only requires "test" to be intern()ed because "compare" is a literal in the source file (which means it's interned already). If it was created in the same way as "test", you'd need to use test.intern() == compare.intern() (and it's usually bad practice unless there's guaranteed to be a relatively small, or at least constrained, number of distinct strings).
Calum
Exactly! Thanks for pointing that out, Calum. Interning strings might be useful for an XML processor or something, where huge numbers of Strings could be created. It's sort of a Flyweight Pattern.
erickson
+5  A: 

Strings in Java are reference types, and == checks whether they are the same string, rather than equal strings. Confusing I know. Long story short you need to do this:

if( test.equals( compare ) ) {

For more you can see here: http://leepoint.net/notes-java/data/strings/12stringcomparison.html

Calum
+3  A: 

You are testing to see if those are the same object, not if they are equal strings.

However the following test will be true:

test.intern() == compare.intern()
sk