Search code examples
javaarraysbyteboxing

How to convert byte[] to Byte[] and the other way around?


How to convert byte[] to Byte[] and also Byte[] to byte[], in the case of not using any 3rd party library?

Is there a way to do it fast just using the standard library?


Solution

  • Byte class is a wrapper for the primitive byte. This should do the work:

    byte[] bytes = new byte[10];
    Byte[] byteObjects = new Byte[bytes.length];
    
    int i=0;    
    // Associating Byte array values with bytes. (byte[] to Byte[])
    for(byte b: bytes)
       byteObjects[i++] = b;  // Autoboxing.
    
    ....
    
    int j=0;
    // Unboxing Byte values. (Byte[] to byte[])
    for(Byte b: byteObjects)
        bytes[j++] = b.byteValue();