getInt(): 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.ByteBuffer.getInt()
This method reads the next four bytes at this buffer's current position, composing them into an int value according to the current byte order, and then increments the position by four.
Parameters: NA
Returns: The int value at the buffer's current position.
Throws:
BufferUnderflowException - If there are fewer than four bytes remaining in this buffer
Java
import java.nio.ByteBuffer;public class ByteBuffergetInt {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4 };ByteBuffer bb = ByteBuffer.wrap(array);System.out.println(bb.getInt());}}
Output:
16909060
Approach 1.1: BufferUnderflowException
Java
import java.nio.ByteBuffer;public class ByteBuffergetInt {public static void main(String[] args) {byte array[] = { 1, 2, 3 };ByteBuffer bb = ByteBuffer.wrap(array);System.out.println(bb.getInt());}}
Output:
Exception in thread "main" java.nio.BufferUnderflowException at java.base/java.nio.Buffer.nextGetIndex(Buffer.java:702) at java.base/java.nio.HeapByteBuffer.getInt(HeapByteBuffer.java:433)
Approach 2: When the method takes an argument of type int.
Syntax:
int java.nio.ByteBuffer.getInt(int index)
This method takes one argument of type int as its parameter. This method reads four bytes at the given index, composing them into an int 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 int value at the given index.
Throws:
IndexOutOfBoundsException - If the index is negative or not smaller than the buffer's limit, minus three
Java
import java.nio.ByteBuffer;public class ByteBuffergetIntint {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 5, 6 };ByteBuffer bb = ByteBuffer.wrap(array);int index = 1;System.out.println(bb.getInt(index));}}
Output:
33752069
Approach 2.1: IndexOutOfBoundsException
Java
import java.nio.ByteBuffer;public class ByteBuffergetIntint {public static void main(String[] args) {byte array[] = { 1, 2, 3, 4, 5, 6 };ByteBuffer bb = ByteBuffer.wrap(array);int index = -1;System.out.println(bb.getInt(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.getInt(HeapByteBuffer.java:438)
No comments:
Post a Comment