CharBuffer clear() methods in Java with Examples
Last Updated :
23 Jul, 2019
The clear() method of java.nio.CharBuffer Class is used to clear this buffer. The position is set to zero, the limit is set to the capacity, and the mark is discarded. Invoke this method before using a sequence of channel-read or put operations to fill this buffer.
For example:
// Prepare buffer for reading
buf.clear();
// Read data
in.read(buf);
This method does not actually erase the data in the buffer, but it is named as if it did because it will most often be used in situations in which that might as well be the case.
Syntax:
public final CharBuffer clear()
Return Value: This method returns this buffer.
Below are the examples to illustrate the clear() method:
Examples 1:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
try {
char [] carr = { 'a' , 'b' , 'c' , 'd' };
CharBuffer cb = CharBuffer.wrap(carr);
cb.position( 2 );
cb.mark();
cb.position( 4 );
System.out.println( "position before reset: "
+ cb.position());
cb.clear();
System.out.println( "position after reset: "
+ cb.position());
}
catch (InvalidMarkException e) {
System.out.println( "new position is less than "
+ "the position we "
+ "marked before " );
System.out.println( "Exception throws: " + e);
}
}
}
|
Output:
position before reset: 4
position after reset: 0
Examples 2:
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
char [] carr = { '.' , '<' , '@' , 'a' };
CharBuffer cb = CharBuffer.wrap(carr);
cb.position( 3 );
System.out.println( "position before clear: "
+ cb.position());
cb.clear();
System.out.println( "position after clear: "
+ cb.position());
}
}
|
Output:
position before clear: 3
position after clear: 0
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/CharBuffer.html#clear–
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...