CharBuffer slice() method in Java
slice() method of java.nio.charBuffer Class is used to create a new char buffer whose content is a shared subsequence of the given buffer’s content. The content of the new buffer will start from this buffer’s current position. The new buffer will show the changes made in the buffer’s content, and vice-versa. The two buffers’ position, limit, and mark values will be independent. The new buffer’s position will be zero, its capacity and its limit will be the number of integers remaining in this buffer, and its mark will be undefined. If, and only if, this buffer is direct then the new buffer will be direct and it will be read-only if, and only if, this buffer is read-only.
Syntax:
public abstract CharBuffer slice()
Return Value: This method returns the new char buffer.
Below are the examples to illustrate the slice() method:
Example 1:
Java
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 10 ;
try {
CharBuffer cb1 = CharBuffer.allocate(capacity);
cb1.put( 'a' );
cb1.put( 'b' );
System.out.println("Original CharBuffer: "
+ Arrays.toString(cb1.array()));
System.out.println("position: " + cb1.position());
System.out.println("capacity: " + cb1.capacity());
CharBuffer cb2 = cb1.slice();
System.out.println("shared subsequence CharBuffer: "
+ Arrays.toString(cb2.array()));
System.out.println("position: " + cb2.position());
System.out.println("capacity: " + cb2.capacity());
}
catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException catched");
}
catch (ReadOnlyBufferException e) {
System.out.println("ReadOnlyBufferException catched");
}
}
}
|
Output:
Original CharBuffer: [a, b, , , , , , , , ]
position: 2
capacity: 10
shared subsequence CharBuffer: [a, b, , , , , , , , ]
position: 0
capacity: 8
Example 2:
Java
import java.nio.*;
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int capacity = 10 ;
try {
CharBuffer cb1 = CharBuffer.allocate(capacity);
cb1.put( 'a' );
cb1.put( 'b' );
cb1.put( 'c' );
cb1.put( 'd' );
System.out.println("Original CharBuffer: "
+ Arrays.toString(cb1.array()));
System.out.println("position: " + cb1.position());
System.out.println("capacity: " + cb1.capacity());
CharBuffer cb2 = cb1.slice();
cb2.put( 'k' );
cb2.put( 'l' );
System.out.println("shared subsequence CharBuffer: "
+ Arrays.toString(cb2.array()));
System.out.println("position: " + cb2.position());
System.out.println("capacity: " + cb2.capacity());
}
catch (IllegalArgumentException e) {
System.out.println("IllegalArgumentException catched");
}
catch (ReadOnlyBufferException e) {
System.out.println("ReadOnlyBufferException catched");
}
}
}
|
Output:
Original CharBuffer: [a, b, c, d, , , , , , ]
position: 4
capacity: 10
shared subsequence CharBuffer: [a, b, c, d, k, l, , , , ]
position: 2
capacity: 6
Last Updated :
16 Nov, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...