The BufferInt asReadOnlyBuffer()
method replicates a buffer in a read-only mode. This means that no modification to the replica buffer content is possible.
The position, mark, and limit of the read-only copy are identical to the original buffer’s position, mark, and limit, but it is independent of the original buffer.
The program needs to include the following module to use the BufferInt asReadOnlyBuffer()
method:
java.nio.IntBuffer
public abstract IntBuffer asReadOnlyBuffer()
The BufferInt asReadOnlyBuffer()
method accepts no parameters and returns a new read-only buffer.
The following example demonstrates how to use the BufferInt asReadOnlyBuffer()
method in Java.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) throws Exception{int cap1 = 5;int cap2 = 10;try {//create buf1IntBuffer buf = IntBuffer.allocate(cap1);//populate buf1buf.put(1,4);buf.put(3,2);buf.put(2,8);buf.rewind();// diplay the IntBufferSystem.out.println("IntBuffer buf: "+ Arrays.toString(buf.array()));//create another IntBufferIntBuffer buf2 = IntBuffer.allocate(cap2);// putting the value in ib1buf2.put(1,5);buf2.put(3,3);buf2.put(2,9);buf2.rewind();// display the IntBufferSystem.out.println("\nIntBuffer ib1: "+ Arrays.toString(buf2.array()));//create a read-pnly copy of buf1IntBuffer readOnlybuf = buf.asReadOnlyBuffer();// display the read only IntBufferSystem.out.print("\nReadOnlyBuffer IntBuffer: ");while (readOnlybuf.hasRemaining())System.out.print(readOnlybuf.get() + ", ");// try to change readOnlyibSystem.out.println("\n\nGet the read only buffer into an array for editing");int[] arr = readOnlybuf.array();}catch (IllegalArgumentException e) {System.out.println("IllegalArgumentException catched");}catch (ReadOnlyBufferException e) {System.out.println("Exception thrown: " + e);}}}
put()
method, and displays them.IntBuffer asReadOnlyBuffer()
method and displays it..array()
method for editing, an exception is thrown because this is not achievable on read-only buffers.