What is the ByteBuffer asIntBuffer() method in Java?

The asIntBuffer() method of the ByteBuffer class in Java creates a view of a given ByteBuffer object as an IntBuffer.

The content of IntBuffer starts from ByteBuffer's current buffer position. Any changes made to ByteBuffer are reflected in IntBuffer, and vice versa.

The position, mark, and limit values of the two buffers are independent.

The process is illustrated below:

To use the asIntBuffer() method, you will need to include the ByteBuffer class in your program, as shown below:

import java.nio.ByteBuffer

The prototype of the asIntBuffer() method is shown below:

public abstract IntBuffer asIntBuffer()

Parameters

The asIntBuffer() method does not accept any parameters.

Return value

The asIntBuffer() method returns a new IntBuffer object that is a view of a specified ByteBuffer object.

The properties of the newly created IntBuffer object are as follows:

  • The current buffer position is set to 00.
  • capacity and limit are defined as the number of bytes that remain in the ByteBuffer object divided by 44.
  • The mark value is undefined.
  • IntBuffer will be direct if, and only if, the ByteBuffer object is direct. Similarly, IntBuffer will be read-only if, and only if, the ByteBuffer object is read-only.

Example

The code below shows how the asIntBuffer() method can be used in Java:

import java.nio.*;
import java.util.*;
class asIntBufferMethod {
public static void main(String[] args) {
// initialize ByteBuffer instance
ByteBuffer sourceBuffer = ByteBuffer.allocate(16);
// get int buffer view
IntBuffer newBuffer = sourceBuffer.asIntBuffer();
int values[] = {2, 1, 6};
// add values to buffer
for(int i = 0; i < 3; i++)
{
newBuffer.put(values[i]);
}
// set buffer position to first index
newBuffer.rewind();
// print source buffer
System.out.println("The ByteBuffer is: " + Arrays.toString(sourceBuffer.array()));
//print new buffer
int i;
System.out.print("The IntBuffer is: [");
while ((i = newBuffer.get()) != 0)
{
System.out.print(i + " ");
}
System.out.print("]");
}
}

Explanation

  • First, a ByteBuffer object, sourceBuffer, is initialized through the allocate() method. sourceBuffer has the capacity to store 1616 elements.

  • Next, an IntBuffer view of sourceBuffer is created through the asIntBuffer() method in line 1111.

  • The put() method is repeatedly invoked through a for-loop to add values to newBuffer.

  • All the changes made to newBuffer are also reflected in sourceBuffer. However, since sourceBuffer holds byte elements, each integer value added to newBuffer is the equivalent of 44 byte values added to sourceBuffer.

For example, the addition of the element 22 to newBuffer is reflected by the addition of 44 elements, i.e., [0,0,0,2][0, 0, 0, 2], to sourceBuffer.

Free Resources