What is the FloatBuffer clear() method in Java?
java.nio.FloatBuffer is a class we can use to store a buffer of floats. We can use the clear() method of this class to clear a buffer. Clearing a buffer means:
- We set the buffer position to 0.
Capacityis the number of elements a buffer contains. Thelimitof a buffer is its first index that should not be read or written. Thelimitof a buffer should be less than or equal to itscapacity. - We set the buffer limit to the buffer capacity.
- We discard the mark.
Markinga position means recording a position that can be restored by theFloatBuffer.reset()method. This marked position is discarded by theFloatBuffer.reset()method.
Declaration
The FloatBuffer.clear() method is declared as follows:
buff.clear()
buff: TheFloatBufferto be cleared.
Return value
The FloatBuffer.clear() method returns the FloatBuffer buff after cleaning it.
Code
Consider the code snippet below, which demonstrates the use of the FloatBuffer.clear() method.
import java.nio.*;import java.util.*;public class main {public static void main(String[] args) {int n1 = 4;FloatBuffer buff1 = FloatBuffer.allocate(n1);buff1.put(1.7F);buff1.put(4.9F);buff1.limit(3);buff1.mark();System.out.println("buff1: " + Arrays.toString(buff1.array()));System.out.println("position at(before clear): " + buff1.position());System.out.println("Limit at(before clear): " + buff1.limit());buff1.mark();System.out.println("clear()");buff1.clear();System.out.println("position at(after rewind): " + buff1.position());System.out.println("Limit at(before clear): " + buff1.limit());}}
Explanation
- A
FloatBufferbuff1is declared in line 7 with the capacityn1 = 4. - Two elements are added to
buff1using theput()method in lines 8-9. After adding the first element, the position ofbuff1is incremented from 0 to 1. After adding the second element, the position ofbuff1is incremented from 1 to 2. - The position of
buff1before clear is 2. After calling theclear()method in line 21, the position ofbuff1is set to 0. - The limit of
buff1is set to 3 using thelimit()method in line 11. The limit ofbuff1beforeclear()is 3. After calling theclear()method in line 21, the limit ofbuff1is set to its capacity, which is 4. - The position of
buff1is marked to 2 using themark()method in line 12. After calling theclear()method in line 21, the mark ofbuff1is discarded and the position is set to 0.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved