FloatBuffer duplicate() method in Java with Examples

The java.nio.The FloatBuffer class has a duplicate() function. To create a new float buffer that shares the contents of the supplied buffer, use the FloatBuffer Class. This buffer's contents will make up the new buffer. The new buffer will reflect changes made to this buffer's content and vice versa; the position, limit, and mark values of the two buffers will remain separate.

The capacity, limit, position, and mark values of the new buffer will be the same as those of the current buffer. The new buffer will be read-only if and only if this buffer is read-only, and it will be direct if and only if this buffer is direct.

Syntax :

Return Value: The previous float buffer content is carried in the new float buffer that is returned by this method.

Example 1:

The Java mentioned above program shows how to generate and duplicate a floating-point number buffer using FloatBuffer. A 10-byte FloatBuffer is allocated, two float values (8.56F and 9.61F) are inserted at certain places, and the buffer is rewound to reset its position. Arrays.toString(floatbuff1.array()) is used to print the contents of the original buffer. Next, the software uses the duplicate() method to produce a duplicate of the FloatBuffer and prints the contents of the duplicate buffer. To detect and manage possible issues during buffer operations, exception handling for ReadOnlyBufferException and IllegalArgumentException is also implemented.

Implementation:

FileName: duplicateFloatExample1.java

Output:

 
The Original FloatBuffer is given by : [8.56, 0.0, 9.61, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
The Duplicate FloatBuffer is given by : [8.56, 0.0, 9.61, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]   

Example 2:

An example of creating, modifying, and copying a FloatBuffer and creating a read-only buffer may be found in the included Java program. Twelve float values (9.32F and 10.23F) are inserted at specified locations in a FloatBuffer that is allocated, and the buffer's position is reset by rewinding it. We can use Arrays.toString(floatbuff1.array()) to print the contents of the original buffer. After using the asReadOnlyBuffer() function to make a read-only copy of the buffer, the program prints the contents of the buffer. In the final step, it uses the duplicate() function to make a copy of this read-only buffer and outputs its contents. A feature of buffer operations is exception management, which is meant to detect and manage possible errors.

Implementation:

FileName: duplicateFloarExample2.java

Output:

 
The Original FloatBuffer is given by: [9.32, 0.0, 0.0, 10.23, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
The read-only FloatBuffer: 9.32, 0.0, 0.0, 10.23, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 
duplicate copy of the read-only FloatBuffer 9.32, 0.0, 0.0, 10.23, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,