Creating strings from bytes / int in Java

I am wondering why the following code is not working:

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!");
}

      

Output:

\\\\\
\\\\\

      

Where is the datatype conversion happening that I don't understand?

Edit: / fail :(

+2


source to share


4 answers


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

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

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



You must do

if(test.equals(compare))

      

+9


source


Strings in Java are reference types, and == checks if they are the same string and not equal strings. I'm embarrassed that I know. In short, you need to do this:

if( test.equals( compare ) ) {



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

+5


source


You are checking if the same objects are the same if they are equal.

However, the following test will be true:

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

      

+3


source


You are using identity comparison, not string comparison.

Try it test.equals(compare)

. Then try it test.intern() == compare

. Both should work. The method intern

is the only reliable way to compare the identity of objects on objects String

.

+2


source







All Articles