2

I wrote this code:

byte[] test = {-51};
byte[] test2 = {-51};
byte[] test3 = {-51};
System.out.println(String.valueOf(test));
System.out.println(String.valueOf(test2));
System.out.println(String.valueOf(test3));

And i've got a different results:

[B@9304b1
[B@190d11
[B@a90653

Why?

5 Answers5

3

The numbers you're seeing are the hash codes of the array objects.

To see the contents of the arrays, use Arrays.toString():

System.out.println(Arrays.toString(test));
System.out.println(Arrays.toString(test2));
System.out.println(Arrays.toString(test3));
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

String.valueOf does not have a byte[] argument, so it will be processed as Object and the toString() method will be called, since arrays doesn't implements this method, Object.toString() will be process in the array and it's result varies from each instance.

If you want to convert byte[] to String use the constructor String(byte[]) or String(byte[] bytes, Charset charset)

byte[] test = {-51};
byte[] test2 = {-51};
byte[] test3 = {-51};
System.out.println(new String(test));
System.out.println(new String(test2));
System.out.println(new String(test3));

Result:

Í
Í
Í

If you want to view the content of the array use the Arrays.toString(byte[])

byte[] test = {-51};
byte[] test2 = {-51};
byte[] test3 = {-51};
System.out.println(Arrays.toString(test));
System.out.println(Arrays.toString(test2));
System.out.println(Arrays.toString(test3));

Result:

[-51]
[-51]
[-51]
Polyana Fontes
  • 3,156
  • 1
  • 27
  • 41
1

the toString pf any array doesn't use the values in the array to create the string you can use Arrays.toString(test); for that

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
0

ValueOf() just calls toString() of given object. If you want to print the content of array use Arrays.toString() instead.

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

Because there is no String.valueOf for a byte array, when you give it byte[], it uses String.valueOf(Object obj).

amphibient
  • 29,770
  • 54
  • 146
  • 240