简体   繁体   中英

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

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM