ByteBuffer getChar() in Java

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

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

Syntax:

char java.nio.ByteBuffer.getChar()

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

Parameters: NA

Returns: The char 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 ByteBuffergetChar {
    public static void main(String[] args) {

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

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

    }
}

Output:

Ă


Approach 1.2: BufferUnderflowException

Java

import java.nio.ByteBuffer;

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

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

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

    }
}


Output:

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


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

Syntax:

char java.nio.ByteBuffer.getChar(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 achar 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 char value at the given index.

Throws:

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

Java

import java.nio.ByteBuffer;

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

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);
        int index = 0;
        System.out.println(bb.getChar(index));

    }
}

Output:

Ă


Approach 2.1: IndexOutOfBoundsException 

Java

import java.nio.ByteBuffer;

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

        byte array[] = { 1234 };
        ByteBuffer bb = ByteBuffer.wrap(array);
        int index = -1;
        System.out.println(bb.getChar(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.getChar(HeapByteBuffer.java:326)


No comments:

Post a Comment