Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

bytebuffer in java

What is ByteBuffer.getLong() method in Java?

Muhammad Ashir

The ByteBuffer.getLong() method in Java is used to read a long value from the associated buffer. It reads eight bytes, starting from the buffer’s current position, and interprets them together as a long value. After reading the value, it increments the position by eight bytes.


public abstract long getLong()


The getLong() method takes in no parameters.

Return value

The getLong() method reads eight bytes from the buffer and returns a long value.


getLong() will throw a BufferUnderflowException exception if there are less than eight bytes left in the buffer.

Sample code

import java.nio.*;
import java.util.*;

class main {
  public static void main( String args[] ) {
        initializing a ByteBuffer with a 
        capacity of 26 bytes
      int capacity = 26;
      ByteBuffer myBuff = ByteBuffer.allocate(capacity);
        Creating a view buffer to be able to 
        insert long values in the buffer
      LongBuffer longBuff = myBuff.asLongBuffer();

      //Inserting values into the buffer
      for (int i = 0; i < capacity/8; i++){

      //Resetting the position
      //Printing the contents of the buffer to STDOUT
      for (int i = 0; i < capacity/8; i++)
        This call throws a BufferUnderFlowException
        (less than 8 bytes left in the buffer)
    catch(BufferUnderflowException e){ //catch the exception
      System.out.println("Can not read a long value from buffer");


In the code above we first create a ByteBuffer object, called myBuff, with a capacity of 2626 (line 12). Its backing array is simply an array of 2626 bytes.

We use the myBuff.asLongBuffer() method to create a view of this buffer as a LongBuffer (line 18), which can read and write long values from its backing array.

Next, we call the put() method to put long values into the buffer using the first for loop (line 11-13).

The longBuff.rewind() method resets the position of the buffer to zero, enabling us to read from the start of the buffer (line 26).

We use the myBuff.getLong() method in the second for loop (line 29-30) to read as many long values from the buffer as the capacity allows, and then print them to the screen.

Lastly, we call the myBuff.getLong() method once again (line 36). However, since we have already read three long values from the buffer, the remaining bytes in the buffer object are two, which is less than the length of a long value, and a BufferUnderFlowException gets thrown.


bytebuffer in java

View all Courses

Keep Exploring