wrap(byte[] array)
The
wrap() method of
java.nio.ByteBuffer Class is used to wraps a byte array into a buffer. The new buffer will be backed by the given byte array, i.e., modifications to the buffer will cause the array to be modified and vice versa. The new buffer's capacity and limit will be array.length, its position will be zero, its mark will be undefined, and its byte order will be
BIG_ENDIAN. It's backing array will be the given array, and its array offset will be zero.
Syntax:
public static ByteBuffer wrap(byte[] array)
Parameters: This method takes
array which is the array that will back this buffer as a parameter.
Return Value: This method returns the new byte buffer.
Below are the examples to illustrate the
wrap() method:
Examples 1:
Output:
Array length: 3
Array element: [10, 20, 30]
byteBuffer: [10, 20, 30]
bytebuffer capacity: 3
bytebuffer position: 0
wrap(byte[] array, int offset, int length)
The new buffer will be backed by the given byte array; that is, modifications to the buffer will cause the array to be modified and vice versa. The new buffer's capacity will be array.length, its position will be offset, its limit will be offset + length, its mark will be undefined, and its byte order will be BIG_ENDIAN. Its backing array will be the given array, and its array offset will be zero.
Syntax:
public static ByteBuffer
wrap(byte[] array, int offset, int length)
Parameters: This method takes following parameters:
- array: The array that will back the new buffer.
- offset: The offset of the subarray to be used; must be non-negative and no larger than array.length. The new buffer's position will be set to this value.
- length: The length of the subarray to be used; must be non-negative and no larger than array.length - offset. The new buffer's limit will be set to offset + length.
Return Value: This method returns the new byte buffer.
Exceptions: This method throws the
IndexOutOfBoundsException(If the preconditions on the offset and length parameters do not hold) .
Below are the examples to illustrate the wrap() method:
Examples 1:
Output:
Array length: 3
Array element: [10, 20, 30]
byteBuffer: [10, 20, 30]
bytebuffer capacity: 3
bytebuffer position: 0
Examples 2: To demonstrate IndexOutOfBoundsException