ByteBuffer asDoubleBuffer() method in Java

Java 8ProgrammingObject Oriented Programming

A view of the ByteBuffer can be created as a DoubleBuffer using the asDoubleBuffer() method in the class java.nio.ByteBuffer. This method requires no parameters and it returns a double 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);
         DoubleBuffer bufferD = bufferB.asDoubleBuffer();
         bufferD.put(4.5D);
         bufferD.put(1.2D);
         bufferD.put(3.9D);
         bufferD.put(7.5D);
         bufferD.put(5.8D);
         bufferD.rewind();
         double d;
         System.out.print("The DoubleBuffer is: ");
         while ((d = bufferD.get()) != 0) {
            System.out.print(d + " ");
         }
      } catch (IllegalArgumentException e) {
         System.out.println("Error!!! IllegalArgumentException");
      } catch (ReadOnlyBufferException e) {
         System.out.println("Error!!! ReadOnlyBufferException");
      }
   }
}

Output

The DoubleBuffer is: 4.5 1.2 3.9 7.5 5.8
raja
Published on 12-Mar-2019 06:28:11
Advertisements