IntBuffer put(int, int[]) in Java

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

Syntax:

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

This method takes two arguments one of type int and another of type int array as its parameters. This method copies ints into this buffer from the given source array.

Note: The position of this buffer is unchanged.

Parameters: Two parameters are required for this method.

index: The index in this buffer at which the first int will be written; must be non-negative and less than limit().

src: The array from which ints are to be read.

Returns: This buffer.

Throws:

1. IndexOutOfBoundsException - If index is negative, not smaller than limit(),or limit() - index < src.length.

2. ReadOnlyBufferException - If this buffer is read-only.

Approach 1: When no exceptions

Java

import java.nio.IntBuffer;

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

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

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

Output:

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


Approach 2: IndexOutOfBoundsException 

Java

import java.nio.IntBuffer;

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

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

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

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [2, 2 + 3) out of bounds for length 4 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromIndexSize(Preconditions.java:82) at java.base/jdk.internal.util.Preconditions.checkFromIndexSize(Preconditions.java:343) at java.base/java.util.Objects.checkFromIndexSize(Objects.java:411) at java.base/java.nio.HeapIntBuffer.put(HeapIntBuffer.java:257) at java.base/java.nio.IntBuffer.put(IntBuffer.java:1189)


Approach 3: ReadOnlyBufferException

Java

import java.nio.IntBuffer;

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

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

        int index = 0;
        int src[] = { 2, 3, 4 };

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

Output:

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



No comments:

Post a Comment