Tony Stark
Tony Stark

Reputation: 25528

Creating Strings from Bytes/Ints in Java

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 :(

Upvotes: 2

Views: 246

Answers (4)

sk.
sk.

Reputation: 6396

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()

Upvotes: 3

Calum
Calum

Reputation: 5926

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

Upvotes: 5

erickson
erickson

Reputation: 269637

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.

Upvotes: 2

Uri
Uri

Reputation: 89729

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))

Upvotes: 9

Related Questions