ByteBuffer put(int, byte) in Java

put(int, byte): This method is available in java.nio.ByteBuffer class of Java.

Syntax:

ByteBuffer java.nio.ByteBuffer.put(int index, byte b)

This method takes two arguments one of type int and another of type byte as its parameters. This method writes the given byte into this buffer at the given index.

Parameters: Two parameters are required for this method.

index: The index at which the byte will be written.

b: The byte value to be written.

Returns: This buffer.

Throws:

1. IndexOutOfBoundsException - If index is negative or not smaller than the buffer's 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 ByteBufferput4 {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        int index = 2;
        byte b = 10;
        System.out.println(Arrays.toString(bb.put(index, b).array()));

    }
}

Output:

[1, 2, 10, 4]


Approach 2: IndexOutOfBoundsException 

Java

import java.nio.ByteBuffer;
import java.util.Arrays;

public class ByteBufferput4 {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        int index = -1;
        byte b = 10;
        System.out.println(Arrays.toString(bb.put(index, b).array()));

    }
}


Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.nio.Buffer.checkIndex(Buffer.java:738) at java.base/java.nio.HeapByteBuffer.put(HeapByteBuffer.java:222)


Approach 3: ReadOnlyBufferException

Java

import java.nio.ByteBuffer;
import java.util.Arrays;

public class ByteBufferput4 {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        ByteBuffer readOnly = bb.asReadOnlyBuffer();
        int index = 2;
        byte b = 10;
        System.out.println(Arrays.toString(readOnly.put(index, b).array()));

    }
}


Output:

Exception in thread "main" java.nio.ReadOnlyBufferException at java.base/java.nio.HeapByteBufferR.put(HeapByteBufferR.java:225)


No comments:

Post a Comment