Q:

Java: How to ensure byte array of size 2 after Hex to binary conversion?

What I am doing:
I have a hex value string strHexVal, which I am assigning to a byte array hexBytes using DatatypeConverter.parseHexBinary(strHexVal)
What I want
The byte array hexBytes should always be of size 2 i.e. if after conversion the size of hexBytes is 1, I would like to insert the array with 0 and if the size after conversion is more than 2, throw an error
Can anyone help me with this? 
Code:
String strHexVal= "15";
byte[] hexBytes = DatatypeConverter.parseHexBinary(strHexVal);

**Need help with this part:**
if ( hexBytes length is 1) {
   hexBytes[1] = hexBytes[0]
   hexBytes[0] = 0x00; //will this work???
}
else if (hexBytes.length > 2) {
   throw error
}

A:

No, you can't just do hexBytes[0] = 0x00; because Java arrays have a fixed size once they are created.
You have to create a new byte[]:
if ( hexBytes.length == 1) {
    hexBytes = new byte[] { 0, hexBytes[0] };
}

Make sure you decide what to do if hexBytes.length is 0 as well. This will be the case if the input string is empty.

