DoubleBuffer clear() methods in Java with Examples

The java.nio.CharBuffer Class has a clear() function in order to clear the buffer. The following are the modifications made when this buffer is cleared:

  • The position is zero.
  • The mark is thrown out when the limit is set to the capacity.

Syntax:

Return Value: After deleting all of the data from it, this function returns this instance of DoubleBuffer.

Example 1:

The code shows how to alter and examine buffer positions and markings in Java using DoubleBuffer. Using an existing double array and the wrap method, a DoubleBuffer is built. The initial position of the buffer is set to index 3, and a mark is created. Clear() is called after the position is changed to index 5, discarding the mark and resetting the buffer's position to 0. Keep in consideration that clear() does not affect the mark; instead, it resets the position to 0 and the limit to the capacity. Since clear() does not interact with the mark in this case, the InvalidMarkException is not thrown.

Implementation:

FileName: BufferClearExample1.java

Output:

 
The position before the reset is given by: 5
The position after the reset is given by: 0   

Example 2:

The code demonstrates how to clear the buffer and manage buffer positions in Java using DoubleBuffer. With wrap, a DoubleBuffer is initialized with an already-existing double array. The position of the buffer is set to index 4, and this value is displayed. The buffer is then reset to its initial position of 0 and its maximum capacity by calling the clear() method. Clear() is called first, and then the new position is printed. Since no mark was set in this code and clear() has no impact on the mark, the InvalidMarkException is not raised.

Implementation:

FileName: BufferClearExample2.java

Output:

 
The position before the reset is given by: 4
The position after the reset is given by: 0