VOOZH about

URL: https://www.geeksforgeeks.org/java/bytebuffer-slice-method-in-java-with-examples/

⇱ ByteBuffer slice() method in Java with Examples - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

ByteBuffer slice() method in Java with Examples

Last Updated : 7 Aug, 2021

The slice() method of java.nio.ByteBuffer Class is used to creates a new byte buffer whose content is a shared subsequence of the given buffer's content.

The content of the new buffer will start at this buffer's current position. Changes to this buffer's content will be visible in the new buffer, 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 floats remaining in this buffer, and its mark will be undefined. The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only.

Syntax : 

public abstract ByteBuffer slice()

Return Value: This method returns the new byte buffer.

Below are the examples to illustrate the slice() method:

Examples 1: 


Output
Original ByteBuffer: [10, 20, 0, 0, 0]

position: 2

capacity: 5

shared subsequence ByteBuffer: [10, 20, 0, 0, 0]

position: 0

capacity: 3

Examples 2:


Output
Original ByteBuffer: [10, 20, 30, 40, 50]

position: 5

capacity: 5

shared subsequence ByteBuffer: [10, 20, 30, 40, 50]

position: 0

capacity: 0

Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#slice--
 

Comment