Byte representations of two identical but unrelated String
objects would most certainly be identical byte-for-byte. However, they would not be the same array object, as long as the String
objects are unrelated.
Your code is checking array equality incorrectly. Here is how you can fix it:
if(Arrays.equals(array1, array2)) ...
Moreover, you would get different byte arrays even if you call getBytes
on the same String
object multiple times:
String test = "test";
byte[] a = test.getBytes();
byte[] b = test.getBytes();
if (a == b) {
System.out.println("same");
} else {
System.out.println("different");
}
The above code prints "different"
.
This is because the String
does not persist the results of getBytes
.
Note: your code does call getBytes
on the same object twice, because this line
String test2 = test1;
does not copy the string, but creates a second reference to the same string object.