put(byte): This method is available in java.nio.ByteBuffer class of Java.
Syntax:
ByteBuffer java.nio.ByteBuffer.put(byte b)
This method takes one argument of type byte as its parameter. This method writes the given byte into this buffer at the current position and then increments the position.
Parameters: One parameter is required for this method.
b: The byte to be written.
Returns: This buffer.
Throws:
1. BufferOverflowException - If this buffer's current position is not smaller than its limit.
2. ReadOnlyBufferException - If this buffer is read-only
Approach 1: When no exceptions.
Java
import java.nio.ByteBuffer;import java.util.Arrays;public class ByteBufferput {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4 };ByteBuffer bb = ByteBuffer.wrap(array);byte b = 5;System.out.println(Arrays.toString(bb.put(b).array()));}}
Output:
[5, 2, 3, 4]
Approach 2: BufferOverflowException
Java
import java.nio.ByteBuffer;import java.util.Arrays;public class ByteBufferput {public static void main(String[] args) {byte array[] = {};ByteBuffer bb = ByteBuffer.wrap(array);byte b = 5;System.out.println(Arrays.toString(bb.put(b).array()));}}
Output:
Exception in thread "main" java.nio.BufferOverflowException at java.base/java.nio.Buffer.nextPutIndex(Buffer.java:717) at java.base/java.nio.HeapByteBuffer.put(HeapByteBuffer.java:212)
Approach 3: ReadOnlyBufferException
Java
import java.nio.ByteBuffer;import java.util.Arrays;public class ByteBufferput {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4 };ByteBuffer bb = ByteBuffer.wrap(array);ByteBuffer readOnly = bb.asReadOnlyBuffer();byte b = 5;System.out.println(Arrays.toString(readOnly.put(b).array()));}}
Output:
Exception in thread "main" java.nio.ReadOnlyBufferException at java.base/java.nio.HeapByteBufferR.put(HeapByteBufferR.java:215)
No comments:
Post a Comment