I would expect the byte representation of two identical strings to also be identical yet this does not seem to be the case. Below is the code I've used to test this.
String test1 = "125";
String test2 = test1;
if(test1.equals(test2))
{
System.out.println("These strings are the same");
}
byte[] array1 = test1.getBytes();
byte[] array2 = test2.getBytes();
if(array1.equals(array2))
{
System.out.println("These bytes are the same");
}
else
{
System.out.println("Bytes are not the same:\n" + array1 + " " + array2);
}
Thanks in advance for your help!
Convert byte[] to String (text data) toString() to get the string from the bytes; The bytes. toString() only returns the address of the object in memory, NOT converting byte[] to a string ! The correct way to convert byte[] to string is new String(bytes, StandardCharsets. UTF_8) .
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.
The issue is that array1.equals(array2)
is not doing what you think it does; it returns equivalent but not reference-identical arrays. If you used Arrays.equals(array1, array2)
, it would have worked.
getBytes() returns different value every time we call on any object so we will get different values when we call like below
System.out.println("1 test1.getBytes() "+test1.getBytes());
System.out.println("2 test2.getBytes() "+test2.getBytes());
both the values are different and storing in a byte[] array1 and byte[] array2 respectively, since both are different bytes , 2 new byte array got created and hence their comparison with equals method compares the references and returns false.
so use Arrays.equals(array1, array2)
this to compare the actual content in those 2 byte arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With