FloatBuffer flip() methods in Java with Examples

The java.nio.FloatBuffer Class has a flip() function. To flip this buffer, use the FloatBuffer Class. The buffer will be truncated to the current location and then the position will be adjusted to zero as a result of flipping this buffer. Any marks that may have been on the buffer throughout this process will be automatically discarded.

Syntax:

Return Value: The reversed instance of FloatBuffer is returned by this method.

Example 1:

The Java code that is given shows how to manage a float array using a FloatBuffer. First, a FloatBuffer called floatBuf is used to wrap a float array doublearr. Next, index 2 is assigned to the buffer's position. The contents, position, and limit of the buffer are printed before flipping. The buffer is then made ready for reading by calling the flip() method, which first sets the buffer's limit to the current position and then resets the position to zero. The buffer's post-flip state, with its contents, location, and limit, is then printed once more to demonstrate the modifications performed by the flip() method.

Implementation:

FileName: flipFloatExample1.java

Output:

 
The Buffer before flip is given by: [11.5, 22.5, 33.5]
The Position is: 2
The Limit is: 3
The Buffer after flip is given by: [11.5, 22.5, 33.5]
The Position is: 0
The Limit is: 2   

Example 2:

The Java code that is given shows how to store and work with float values using a FloatBuffer. It starts by allocating a 4-capacity FloatBuffer, and then it uses the put() method to insert two float values. Next, index 1 is assigned to the buffer's position. The buffer's position, limit, and contents are all shown both before and after the flip() method is called. By first setting the limit to the current position and then resetting the position to 0, the flip() method reads the buffer from the start up to the new limit, ready to receive the added float values.

Implementation:

FileName: flipFloatExample2 .java

Output:

 
The Buffer before flip is given by: [9.56, 12.5, 0.0, 0.0]
The Position: 1
The Limit: 4
The Buffer after flip is given by: [9.56, 12.5, 0.0, 0.0]
The Position: 0
The Limit: 1