IntBuffer put() method in Java

The required value can be written at the current position of the buffer and then the current position is incremented using the method put() in the class java.nio.IntBuffer. This method requires a single parameter i.e. the value to be written in the buffer and it returns the buffer in which the value is inserted.

A program that demonstrates this is given as follows −


 Live Demo

import java.nio.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      int n = 5;
      try {
         IntBuffer buffer = IntBuffer.allocate(5);
         System.out.println("The IntBuffer is: " + Arrays.toString(buffer.array()));
      } catch (BufferOverflowException e) {
         System.out.println("Error!!! BufferOverflowException");
      } catch (ReadOnlyBufferException e) {
         System.out.println("Error!!! ReadOnlyBufferException");

The output of the above program is as follows −


The IntBuffer is: [8, 1, 3, 7, 5]
Samual Sam
Samual Sam

Learning faster. Every day.