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 i)

This method takes one argument of type int as its parameter. This method writes the given int into this buffer at the current position and then increments the position.

Parameters: One parameter is required for this method.

i: The int 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.IntBuffer;

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

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

Output:

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


Approach 2: BufferOverflowException 

Java

import java.nio.IntBuffer;

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

        int array[] = {};
        IntBuffer lb = IntBuffer.wrap(array);
        int l = 1919;
        System.out.println(lb.put(l));
    }
}

Output:

Exception in thread "main" java.nio.BufferOverflowException at java.base/java.nio.Buffer.nextPutIndex(Buffer.java:717) at java.base/java.nio.HeapIntBuffer.put(HeapIntBuffer.java:212)



Approach 3: ReadOnlyBufferException

Java

import java.nio.IntBuffer;

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

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

        IntBuffer readOnly = lb.asReadOnlyBuffer();
        int l = 1919;
        System.out.println(readOnly.put(l));
    }
}

Output:

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



No comments:

Post a Comment