How to use the BufferInt asReadOnlyBuffer() method in Java

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

Syntax

public abstract IntBuffer asReadOnlyBuffer()

Parameters and return value

The BufferInt asReadOnlyBuffer() method accepts no parameters and returns a new read-only buffer.

Example

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 buf1
IntBuffer buf = IntBuffer.allocate(cap1);
//populate buf1
buf.put(1,4);
buf.put(3,2);
buf.put(2,8);
buf.rewind();
// diplay the IntBuffer
System.out.println("IntBuffer buf: "+ Arrays.toString(buf.array()));
//create another IntBuffer
IntBuffer buf2 = IntBuffer.allocate(cap2);
// putting the value in ib1
buf2.put(1,5);
buf2.put(3,3);
buf2.put(2,9);
buf2.rewind();
// display the IntBuffer
System.out.println("\nIntBuffer ib1: "+ Arrays.toString(buf2.array()));
//create a read-pnly copy of buf1
IntBuffer readOnlybuf = buf.asReadOnlyBuffer();
// display the read only IntBuffer
System.out.print("\nReadOnlyBuffer IntBuffer: ");
while (readOnlybuf.hasRemaining())
System.out.print(readOnlybuf.get() + ", ");
// try to change readOnlyib
System.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);
}
}
}
  • The program creates two buffers, populates them using the put() method, and displays them.
  • It then creates a read-only copy of the first buffer using the IntBuffer asReadOnlyBuffer() method and displays it.
  • When we try to get an array of the buffer using the .array() method for editing, an exception is thrown because this is not achievable on read-only buffers.
Copyright ©2024 Educative, Inc. All rights reserved