What is the ByteBuffer getInt() method in Java?

Overview

The getInt method is defined for the ByteBuffer class in Java. The getInt method reads the next 4 bytes in the ByteBuffer and returns it as an int. If the index parameter variant of this method is used, then the position from which the bytes are read is specified by the index argument.

Syntax

public abstract int getInt()
public abstract int getInt(int index)

Parameters

  • index is an integer that specifies the index of the ByteBuffer from where the bytes are to be read.

Return value

  • An instance of int that is composed of the 4 bytes read from the ByteBuffer instance is returned.

Exceptions

  • BufferUnderflowException is thrown if less than 4 bytes remain in ByteBuffer.

Example

import java.nio.*;
class Program {
public static void main( String args[] ) {
try {
ByteBuffer buffer = ByteBuffer.allocate(20);
buffer.asIntBuffer().put(100).put(200).put(300);
System.out.println("Buffer Data: ");
System.out.println(buffer.getInt());
System.out.println(buffer.getInt());
System.out.println(buffer.getInt());
System.out.println("\nBuffer Data at index 0:");
System.out.println(buffer.getInt(0));
} catch (BufferUnderflowException err) {
System.out.println("\nError: " + err);
}
}
}

In the example above, a ByteBuffer of size 20 bytes is initialized and stored in the buffer variable. Using the asIntBuffer method, we treat this byte buffer as an IntBuffer to put the integer values 100, 200, and 300 as 4 bytes each in the buffer. Then, we invoke the getInt method without the index argument to get the integers and print them on the standard output. Lastly, we also read and print the first integer inside the buffer by specifying the index argument as 0.

Copyright ©2024 Educative, Inc. All rights reserved