IntBuffer put(IntBuffer) in Java

put(IntBuffer): This method is available in java.nio.IntBuffer class of Java.

Syntax:

IntBuffer java.nio.IntBuffer.put(IntBuffer src)

This method takes one argument of type IntBuffer as its parameter. This method transfers the ints remaining in the given source buffer into this buffer.

Parameters: One parameter is required for this method.

src: The source buffer from which ints are to be read;must not be this buffer.

Returns: This buffer.

Throws:

1. BufferOverflowException - If there is insufficient space in this buffer for the remaining ints in the source buffer.

2. IllegalArgumentException - If the source buffer is this buffer.

3. ReadOnlyBufferException - If this buffer is read-only

Approach 1: When no exceptions

Java

import java.nio.IntBuffer;

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

        int array[] = { 1, 2, 3, 4 };
        IntBuffer lb = IntBuffer.wrap(array);

        int array2[] = { 1, 2, 3 };
        IntBuffer src = IntBuffer.wrap(array2);
        System.out.println(lb.put(src));
    }
}

Output:

java.nio.HeapIntBuffer[pos=3 lim=4 cap=4]


Approach 2: BufferOverflowException

Java

import java.nio.IntBuffer;

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

        int array[] = { 1, 2, 3, 4 };
        IntBuffer lb = IntBuffer.wrap(array);

        int array2[] = { 1, 2, 3, 4, 5, 6 };
        IntBuffer src = IntBuffer.wrap(array2);
        System.out.println(lb.put(src));
    }
}

Output:

Exception in thread "main" java.nio.BufferOverflowException at java.base/java.nio.IntBuffer.put(IntBuffer.java:957) at java.base/java.nio.HeapIntBuffer.put(HeapIntBuffer.java:247)


Approach 3: IllegalArgumentException 

Java

import java.nio.IntBuffer;

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

        int array[] = { 1, 2, 3, 4 };
        IntBuffer lb = IntBuffer.wrap(array);
        System.out.println(lb.put(lb));
    }
}

Output:

Exception in thread "main" java.lang.IllegalArgumentException: The source buffer is this buffer at java.base/java.nio.Buffer.createSameBufferException(Buffer.java:261) at java.base/java.nio.IntBuffer.put(IntBuffer.java:949) at java.base/java.nio.HeapIntBuffer.put(HeapIntBuffer.java:247)


Approach 4: ReadOnlyBufferException

Java

import java.nio.IntBuffer;

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

        int array[] = { 1, 2, 3, 4 };
        IntBuffer lb = IntBuffer.wrap(array);

        int array2[] = { 1, 2, 3 };
        IntBuffer src = IntBuffer.wrap(array2);

        IntBuffer readOnly = lb.asReadOnlyBuffer();
        System.out.println(readOnly.put(src));
    }
}

Output:

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


No comments:

Post a Comment