What is the floatBuffer wrap() method in Java?

The wrap() method is one of the methods in the java.nio.FloatBuffer class. This method wraps a float array into a buffer. Wrapping means that the buffer encloses the float array. This function takes a float array as a parameter.

Any changes in the buffer will automatically cause changes in the array as well.

Key points

  1. The buffer limit will be equal to the length of the array.

  2. The buffer position will be equal to 0.

  3. Backing array will be equal to the array provided.

Converting arrays to lists creates these array-backed lists, which point to the same data stored in a heap.

Syntax

FloatBuffer.wrap(array)

array: The float array backing the buffer.

Return value

The method returns a new float buffer.

Code

Here is an example of the wrap method.

import java.nio.*;
import java.util.*;
class HelloWorld {
public static void main( String args[] ) {
float[] array = { 3.2F, 3.5F, 6.7F };
// print the array
System.out.println("Array length : " + array.length + ", elements : "+ Arrays.toString(array));
// using wrap() on the array
FloatBuffer buff = FloatBuffer.wrap(array);
// printing floatbuffer array
System.out.println("Buffer cap : " + buff.capacity() +
", position : "+ buff.position() + ", elements "+ Arrays.toString(buff.array()));
// changing the buffer
buff.put(1.2F);
System.out.println("Buffer cap : " + buff.capacity() +
", position : "+ buff.position() + ", elements "+ Arrays.toString(buff.array()));
}
}
Copyright ©2024 Educative, Inc. All rights reserved