ByteBuffer asLongBuffer() method in Java


A view of the ByteBuffer can be created as a LongBuffer using the asLongBuffer() method in the class java.nio.ByteBuffer. This method requires no parameters and it returns a long buffer as required. This buffer reflects the changes made to the original buffer and vice versa.

A program that demonstrates this is given as follows −

Example

 Live Demo

import java.nio.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      int n = 50;
      try {
         ByteBuffer bufferB = ByteBuffer.allocate(n);
         LongBuffer bufferL = bufferB.asLongBuffer();
         bufferL.put(5000);
         bufferL.put(9000);
         bufferL.put(2000);
         bufferL.put(8000);
         bufferL.put(3000);
         bufferL.rewind();
         long l;
         System.out.print("The LongBuffer is: ");
         while ((l = bufferL.get()) != 0) {
            System.out.print(l + " ");
         }
      } catch (IllegalArgumentException e) {
         System.out.println("Error!!! IllegalArgumentException");
      } catch (ReadOnlyBufferException e) {
         System.out.println("Error!!! ReadOnlyBufferException");
      }
   }
}

Output

The LongBuffer is: 5000 9000 2000 8000 3000

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

54 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements