ByteBuffer asIntBuffer() method in Java


A view of the ByteBuffer can be created as an IntBuffer using the asIntBuffer() method in the class java.nio.ByteBuffer. This method requires no parameters and it returns an int buffer as required. This buffer reflects the changes made to the original buffer and vice versa.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.nio.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      int n = 50;
      try {
         ByteBuffer bufferB = ByteBuffer.allocate(n);
         IntBuffer bufferI = bufferB.asIntBuffer();
         bufferI.put(3);
         bufferI.put(9);
         bufferI.put(1);
         bufferI.put(7);
         bufferI.put(4);
         bufferI.rewind();
         int i;
         System.out.print("The IntBuffer is: ");
         while ((i = bufferI.get()) != 0) {
            System.out.print(i + " ");
         }
      } catch (IllegalArgumentException e) {
         System.out.println("Error!!! IllegalArgumentException");
      } catch (ReadOnlyBufferException e) {
         System.out.println("Error!!! ReadOnlyBufferException");
      }
   }
}

Output

The IntBuffer is: 3 9 1 7 4

Updated on: 30-Jul-2019

62 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements