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 :(
source to share
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))
source to share
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
source to share