ByteBuffer limit() in Java

limit(): 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.limit()

This method returns this buffer's limit.

Parameters: NA

Returns: The limit of this buffer.

Exceptions: NA

Java

import java.nio.ByteBuffer;

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

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

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

    }
}

Output:

4


Approach 2: When the method takes one argument of type int.

Syntax:

ByteBuffer java.nio.ByteBuffer.limit(int newLimit)

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

Parameters: One parameter is required for this method.

newLimit: The new limit value; must be non-negative and no larger than this buffer's capacity.

Returns: This buffer.

Exceptions: IllegalArgumentException

Java

import java.nio.ByteBuffer;

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

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

        int newLimit = 3;
        System.out.println(bb.limit(newLimit));

    }
}

Output:

java.nio.HeapByteBuffer[pos=0 lim=3 cap=4]


Approach 2.1: IllegalArgumentException

Java

import java.nio.ByteBuffer;

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

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

        int newLimit = 10;
        System.out.println(bb.limit(newLimit));

    }
}


Output:

Exception in thread "main" java.lang.IllegalArgumentException: newLimit > capacity: (10 > 4) at java.base/java.nio.Buffer.createLimitException(Buffer.java:391) at java.base/java.nio.Buffer.limit(Buffer.java:365) at java.base/java.nio.ByteBuffer.limit(ByteBuffer.java:1382)


No comments:

Post a Comment