Share on Google+Share on Google+

Creates a read-only int buffer that shares the content of int buffer.

Advertisement
In this tutorial you will see how to creates a read-only int buffer that shares the content of int buffer.

Creates a read-only int buffer that shares the content of int buffer.

In this tutorial, we will see how to creates a read-only int buffer that shares the content of int buffer.

IntBuffer API :

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

Return type Method Description
static IntBuffer allocate( int capacity)  The allocate(..) method allocate a new int buffer.
abstract IntBuffer asReadOnlyBuffer() The asReadOnlyBuffer() method create a new read-only buffer that share the content of given int buffer.

Code

import java.nio.*;
import java.nio.IntBuffer;

public class ReadOnlyIntBuffer {
  public static void main(String[] argsthrows Exception{
    int[] array=new int[]{4,5};
  IntBuffer intBuf = IntBuffer.wrap(array);  
    System.out.println("Content in int buffer.");
    while (intBuf.hasRemaining()) {
      System.out.println(intBuf.get());
    }
    IntBuffer readIntBuffer = intBuf.asReadOnlyBuffer();
    readIntBuffer.flip();
    System.out.println("Content in int readOnlyBuffer.");
    while (readIntBuffer.hasRemaining()) {
      System.out.println(readIntBuffer.get());
    }
    try {
      readIntBuffer.put(23);
    catch (Exception e) {
      System.out.println("Buffer is read_only : " + e);
    }
  }
}

Output

C:\>java ReadOnlyIntBuffer
Content in int buffer.
4
5
Content in int readOnlyBuffer.
4
5
Buffer is read_only : java.nio.ReadOnlyBufferException

Download this code

Advertisements

Posted on: August 3, 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.