ByteBuffer position() in Java

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

Approach 1: When the method does not take any argument.

Syntax:

int java.nio.Buffer.position()

This method returns this buffer's position.

Parameters: NA

Returns: The position of this buffer.

Exceptions: NA

Java

import java.nio.ByteBuffer;

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

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

        System.out.println(bb.position());

    }
}

Output:

0


Approach 2: When the method takes an argument.

Syntax:

ByteBuffer java.nio.ByteBuffer.position(int newPosition)

This method sets this buffer's position. If the mark is defined and larger than the new position then it is discarded.

Parameters: One parameter is required for this method.

newPosition: The new position value; must be non-negative and no larger than the current limit.

Returns: This buffer.

Exceptions: NA

Java

import java.nio.ByteBuffer;

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

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

        int newPosition = 2;
        System.out.println(bb.position(newPosition));

    }
}

Output:

java.nio.HeapByteBuffer[pos=2 lim=4 cap=4]

No comments:

Post a Comment