-1

I've been implementing an Android app which communicates with a Java server, and they send byte arrays back and fourth. When I use Arrays.toString(byte[]) then everything works as expected, however this is not the case with printing to the console. Here I print a byte array to the console in Android:

Log.d("byte array test"" + new byte[]{109, 89, -47, 12, 80, -13, 27, -9, 1, 117, -128, -98, 31, 2, -79, -36, -38, 78, -88, 74, 78, 105, 8, -53, 63, -96, -126, 85, -63, -105, 96, 124});

Which produces the following output:

D/byte array test: [B@b4938b

On Java:

System.out.println( new byte[]{109, 89, -47, 12, 80, -13, 27, -9, 1, 117, -128, -98, 31, 2, -79, -36, -38, 78, -88, 74, 78, 105, 8, -53, 63, -96, -126, 85, -63, -105, 96, 124}  "");

Which produces the following output:

[B@43556938

Can anyone explain why? To the best of my understanding, they're both strings, so they both should produce the same output. Encoding is the only reason I could think of a difference, but I don't have much experience with that, so I'm not sure.

Alex Jone
  • 292
  • 2
  • 14

2 Answers2

2

The array uses the default Object.toString() method to be printed, and this method uses the Object.hashcode() method for this.

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

In the docs you can see that the default implementation of hashcode uses the internal address of the object, so is normal that they do not match given that they are not the same object (or aren't located in the same address).

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)

So when the arrays are different objects, like the ones:

byte[] bytes1 = new String("HelloWorld").getBytes();
byte[] bytes2 = new String("HelloWorld").getBytes();

Both arrays contains exactly the same elements, but they are different objects (and are stored in diffent addresses), so if you print then you will see different values.

System.out.println(bytes1); // [B@7cc355be in my case
System.out.println(bytes2); // [B@6e8cf4c6 in my case
Jose Da Silva Gomes
  • 3,814
  • 3
  • 24
  • 34
1

This is just printing the array reference instead of the values inside it. To get the exact values you can use, Arrays.toString

It will definitely call the to string method, but the way toString is implemented in Object class is it prints the name of the class followed by hashcode:

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

Now, object hashcode is a native implementation which provides integer format of object reference and hence it will be different for the two cases you are checking above.

Aman Chhabra
  • 3,824
  • 1
  • 23
  • 39