How do I initialize a byte array in Java?
To initialize a byte array in Java, you can use the array initializer syntax, like this:
byte[] bytes = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09};
This will create an array of bytes with the specified values.
Alternatively, you can use the new
operator to create an array of a specified size and then assign values to its elements:
byte[] bytes = new byte[10];
bytes[0] = 0x00;
bytes[1] = 0x01;
bytes[2] = 0x02;
// ...
You can also use a loop to initialize the array with a series of values:
byte[] bytes = new byte[10];
for (int i = 0; i < 10; i++) {
bytes[i] = (byte)i;
}
Note that the size of a byte array is fixed and cannot be changed after it is created. If you need to change the size of the array, you can create a new array with the desired size and copy the elements of the old array to the new array using the System.arraycopy()
method.
Here's an example of how to do this:
byte[] oldBytes = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05};
byte[] newBytes = new byte[10];
System.arraycopy(oldBytes, 0, newBytes, 0, oldBytes.length);
This will create a new byte array newBytes
with size 10 and copy the elements of the old byte array oldBytes
to it. The elements that do not fit in the new array will be truncated.