IntBuffer slice(int, int) in Java

slice(int, int): This method is available in java.nio.IntBuffer class of Java.

Syntax:

IntBuffer java.nio.IntBuffer.slice(int index, int length)

This method takes two arguments of type int as its parameters. This method creates a new int buffer whose content is a shared subsequence of this buffer's content. The content of the new buffer will start at the position index in this buffer and will contain length elements.

Parameters: Two parameters are required for this method.

index: The position in this buffer at which the content of the new buffer will start; must be non-negative and no larger than the limit().

length: The number of elements the new buffer will contain; must be non-negative and no larger than the limit() - index.

Returns: The new buffer.

Throws:

1. IndexOutOfBoundsException - If index is negative or greater than limit(), length is negative, or length > limit() - index.

Approach 1: When no exceptions

Java

import java.nio.IntBuffer;

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

        int array[] = { 1, 2, 3, 4 };
        IntBuffer lb = IntBuffer.wrap(array);

        int index = 0, length = 2;
        System.out.println(lb.slice(index, length));
    }
}

Output:

java.nio.HeapIntBuffer[pos=0 lim=2 cap=2]


Approach 2: IndexOutOfBoundsException

Java

import java.nio.IntBuffer;

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

        int array[] = { 1, 2, 3, 4 };
        IntBuffer lb = IntBuffer.wrap(array);

        int index = 3, length = 2;
        System.out.println(lb.slice(index, length));
    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Range [3, 3 + 2) out of bounds for length 4 at java.base/jdk.internal.util.Preconditions.outOfBounds(Preconditions.java:64) at java.base/jdk.internal.util.Preconditions.outOfBoundsCheckFromIndexSize(Preconditions.java:82) at java.base/jdk.internal.util.Preconditions.checkFromIndexSize(Preconditions.java:343) at java.base/java.util.Objects.checkFromIndexSize(Objects.java:411) at java.base/java.nio.HeapIntBuffer.slice(HeapIntBuffer.java:121)


No comments:

Post a Comment