ByteBuffer.wrap(): This method is available in java.nio.ByteBuffer class of Java.
Approach 1: When the method takes one argument.
Syntax:
ByteBuffer java.nio.ByteBuffer.wrap(byte[] array)
This method takes one argument of type byte array as it parameter. This method wraps a byte array into a buffer. 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 and limit will be array.length, its position will be zero, 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.
Parameters: One parameter is required for this method.
array: The array that will back this buffer.
Returns: The new byte buffer.
Exceptions: NA
Java
import java.nio.ByteBuffer;public class ByteBufferwrap {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 7 };System.out.println(ByteBuffer.wrap(array));}}
Output:
java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
Approach 2: When the method takes three arguments.
Syntax:
ByteBuffer java.nio.ByteBuffer.wrap(byte[] array, int offset, int length)
This method takes three arguments one of type byte array and the rest two are of type int as its parameter. This method wraps a byte array into a buffer. 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.
Parameters: Three parameters are required for this method.
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 the array.length - offset. The new buffer's limit will be set to offset + length.
Returns: The new byte buffer.
Throws:
1. IndexOutOfBoundsException - If the preconditions on the offset and length parameters do not hold.
Java
import java.nio.ByteBuffer;public class ByteBufferwrap2 {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 5, 6 };int offset = 0, length = 3;ByteBuffer bb = ByteBuffer.wrap(array, offset, length);System.out.println(bb);}}
Output:
java.nio.HeapByteBuffer[pos=0 lim=3 cap=6]
Approach 2.1: IndexOutOfBoundsException
Java
import java.nio.ByteBuffer;public class ByteBufferwrap2 {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 5, 6 };int offset = 2, length = 5;ByteBuffer bb = ByteBuffer.wrap(array, offset, length);System.out.println(bb);}}
Output:
Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.nio.ByteBuffer.wrap(ByteBuffer.java:408)
No comments:
Post a Comment