Search code examples
javastringvalue-of

java String.valueOf issue


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?


Solution

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