ByteBuffer duplicate() in Java

duplicate(): This method is available in java.nio.ByteBuffer class of Java.

Syntax:

ByteBuffer java.nio.ByteBuffer.duplicate()

This method creates a new byte buffer that shares this buffer's content. The content of the new buffer will be that of this buffer. Changes to this buffer's content will be visible in the new buffer, and vice versa; the two buffers' position, limit, and mark values will be independent.

Note: The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only.

Returns: The new byte buffer.

Exceptions: NA

Approach

Java

import java.nio.ByteBuffer;
import java.util.Arrays;

public class ByteBufferduplicate {
    public static void main(String[] args) {

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);

        ByteBuffer newBB = bb.duplicate();
        System.out.println("Original ByteBuffer is " + 
Arrays.toString(bb.array()));
        System.out.println("Duplicate ByteBuffer is " + 
Arrays.toString(newBB.array()));

    }
}


Output:

Original ByteBuffer is [1, 2, 3, 4] Duplicate ByteBuffer is [1, 2, 3, 4]


No comments:

Post a Comment