ByteBuffer asFloatBuffer() method in Java


A view of the ByteBuffer can be created as a FloatBuffer using the asFloatBuffer() method in the class java.nio.ByteBuffer. This method requires no parameters and it returns a float 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);
         FloatBuffer bufferF = bufferB.asFloatBuffer();
         bufferF.put(3.5F);
         bufferF.put(9.7F);
         bufferF.put(1.2F);
         bufferF.put(7.5F);
         bufferF.put(4.6F);
         bufferF.rewind();
         float f;
         System.out.print("The FloatBuffer is: ");
         while ((f = bufferF.get()) != 0) {
            System.out.print(f + " ");
         }
      } catch (IllegalArgumentException e) {
         System.out.println("Error!!! IllegalArgumentException");
      } catch (ReadOnlyBufferException e){
         System.out.println("Error!!! ReadOnlyBufferException");
      }
   }
}

Output

The FloatBuffer is: 3.5 9.7 1.2 7.5 4.6

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements