IntBuffer put(int[]) in Java

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

Syntax:

IntBuffer java.nio.IntBuffer.put(int[] src)

This method takes one argument of type int array as its parameter. This method transfers the entire content of the given source int array into this buffer.

Parameters: One parameter is required for this method.

src: The source array.

Returns: This buffer.

Throws:

1. BufferOverflowException - If there is insufficient space in this buffer.

2. ReadOnlyBufferException - If this buffer is read-only

Approach 1: When no exceptions

Java

import java.nio.IntBuffer;

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

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

        int src[] = { 1, 2, 3 };
        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 IntBufferput2 {
    public static void main(String[] args) {

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

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

Output:

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



Approach 3: ReadOnlyBufferException 

Java

import java.nio.IntBuffer;

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

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

        IntBuffer readOnly = lb.asReadOnlyBuffer();

        int src[] = { 1, 2, 3 };
        System.out.println(readOnly.put(src));
    }
}

Output:

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



No comments:

Post a Comment