Java: Same string returns different byte arrays -
i expect byte representation of 2 identical strings identical yet not seem case. below code i've used test this.
string test1 = "125"; string test2 = test1; if(test1.equals(test2)) { system.out.println("these strings same"); } byte[] array1 = test1.getbytes(); byte[] array2 = test2.getbytes(); if(array1.equals(array2)) { system.out.println("these bytes same"); } else { system.out.println("bytes not same:\n" + array1 + " " + array2); }
thanks in advance help!
byte representations of 2 identical unrelated string
objects identical byte-for-byte. however, not the same array object, long string
objects unrelated.
your code checking array equality incorrectly. here how can fix it:
if(arrays.equals(array1, array2)) ...
moreover, different byte arrays if call getbytes
on same string
object multiple times:
string test = "test"; byte[] = test.getbytes(); byte[] b = test.getbytes(); if (a == b) { system.out.println("same"); } else { system.out.println("different"); }
the above code prints "different"
.
this because string
not persist results of getbytes
.
note: code call getbytes
on same object twice, because line
string test2 = test1;
does not copy string, creates second reference same string object.
Comments
Post a Comment