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 −


 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();
         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");


The IntBuffer is: 3 9 1 7 4
karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know