ByteBuffer getShort() in Java

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

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

Syntax:

short java.nio.ByteBuffer.getShort()

This method reads the next two bytes at this buffer's current position, composing them into a short value according to the current byte order, and then increments the position by two.

Parameters: NA

Returns: The short value at the buffer's current position.

Throws:

BufferUnderflowException - If there are fewer than two bytes remaining in this buffer

Java

import java.nio.ByteBuffer;

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

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

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

    }
}

Output:

258


Approach 1.1: BufferUnderflowException

Java

import java.nio.ByteBuffer;

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

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

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

    }
}


Output:

Exception in thread "main" java.nio.BufferUnderflowException at java.base/java.nio.Buffer.nextGetIndex(Buffer.java:702) at java.base/java.nio.HeapByteBuffer.getShort(HeapByteBuffer.java:377)


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

Syntax:

short java.nio.ByteBuffer.getShort(int index)

This method takes one argument of type int as its parameter. This method reads two bytes at the given index, composing them into a short value according to the current byte order.

Parameters: One parameter is required for this method.

index: The index from which the bytes will be read.

Returns: The short value at the given index.

Throws:

IndexOutOfBoundsException - If the index is negative or not smaller than the buffer's limit, minus one

Java

import java.nio.ByteBuffer;

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

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

        int index = 2;
        System.out.println(bb.getShort(index));

    }
}

Output:

772


Approach 2.1: IndexOutOfBoundsException 

Java

import java.nio.ByteBuffer;

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

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

        int index = -1;
        System.out.println(bb.getShort(index));

    }
}

Output:

Exception in thread "main" java.lang.IndexOutOfBoundsException at java.base/java.nio.Buffer.checkIndex(Buffer.java:744) at java.base/java.nio.HeapByteBuffer.getShort(HeapByteBuffer.java:382)


No comments:

Post a Comment