Question

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?

Was it helpful?

Solution 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]

OTHER TIPS

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));

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

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

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top