FloatBuffer clear() methods in Java with Examples

The java.nio.FloatBuffer Class's clear() function is used to clear this buffer. The mark has been eliminated using the above method, which sets the position and limit to zero and capacity, respectively. When a specific order of channel read or put operations is required, this procedure needs to be called upon. To put it another way, the clear() method sets the position to zero and prepares the buffer for reading if it is necessary.

Although the method is named as though it eliminates the data in the buffer, it does not actually do so because it is most frequently used in scenarios when deletion might as well be the case.

Syntax:

Parameters: There are no parameters required by the method.

Return Value: This function removes all of the data from the FloatBuffer and returns this instance.

Example 1:

The Java code shows how to use a FloatBuffer. The float array is wrapped to produce a FloatBuffer, and the buffer's location is set to index 3 and marked at this point. After that, it prints the current position and shifts the position to index 2. When the buffer is reset using the clear technique, the mark is discarded, and the position is reset to 0. After clearing the buffer, it prints the new position at the end. If an attempt is made to set a position outside of the buffer's bounds, the function contains error handling to capture and throw any IllegalArgumentException.

Implementation:

FileName: clearFloatExample1.java

Output:

 
The position before reset is given by: 2
The position after reset is given by: 0   

Example 2:

The code contains an array of floats and modifies its location to show how to use a FloatBuffer in Java. The buffer is created with an array of four float values, and its location is set to index 4, which is illegal because it goes outside the confines of the array. After that, the current position is printed. To reset the buffer, remove all markings, and return the position to 0, the clear method is called. When the buffer has been cleared, it publishes the position at the end. Keep in consideration that trying to set the position to 4 ought to result in an IllegalArgumentException being thrown.

Implementation:

FileName: clearFloatExample2.java

Output:

 
The position before clear is given by : 4
The position after clear is given by : 0