Share on Google+Share on Google+

How to create a int buffer with the help of byte buffer.

Advertisement
In this tutorial you will see how to create a int buffer with the help of byte buffer.

How to create a int buffer with the help of byte buffer.

 In this tutorial, we will see how to create a int buffer with the help of byte buffer.

ByteBuffer API:

The java.nio.ByteBuffer class extends java.nio.Buffer class. It provides the following methods:

Return type Method Description
static ByteBuffer allocate( int capacity)  The allocate() method allocate a byte buffer of given capacity. 
 abstrtact IntBuffer  asIntBuffer() The asIntBuffer() method returns int buffer based in byte buffer.

Buffer API:

The java.nio.Buffer class extends java.lang.Object class. It provides the following methods:

Return type Method Description
int limit() The limit() method returns the limit of int buffer.
int position() The position() method returns the position of int buffer.
final int capacity() The capacity() method returns the capacity of associated int buffer.

Code

import java.nio.*;
import java.nio.IntBuffer;
import java.nio.ByteBuffer;
public class IntBufferDemo {
  public static void main(String[] argsthrows Exception {
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    int[] array = new int[] { 123};
    IntBuffer IntBuf = byteBuffer.asIntBuffer();
    IntBuf.put(array);
    System.out.println("\nContent of int buffer.");
    IntBuf.flip();
    while (IntBuf.hasRemaining()) {
      System.out.println(IntBuf.get());
    }
System.out.println("Position of IntBuffer :" + IntBuf.position());
    System.out.println("Limit of IntBuffer :" + IntBuf.limit());
System.out.println("Capacity of IntBuffer :" + IntBuf.capacity());
  }
}

Output

C:\>java IntBufferDemo
Content of int buffer.
1
2
3
4
Position of IntBuffer :4
Limit of IntBuffer :4
Capacity of IntBuffer :256

Download this code

Advertisements

Advertisement

Posted on: August 2, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.