The FloatBuffer slice
method creates a new buffer from the this
buffer. The new buffer shares a slice of the this
buffer, which means any changes in the new buffer is reflected in the this
buffer and vice versa.
The program needs to include the following header to use the FloatBuffer slice()
method:
java.nio.FloatBuffer
public abstract FloatBuffer slice()
The FloatBuffer slice()
method accepts no parameters and returns a new float buffer that shares a slice of the original buffer.
The mark, limit, and position of the new buffer are independent of the original buffer.
The new buffer starts from the current position in the original buffer. The position of the new buffer is set to zero, and the mark is undefined. In contrast, the limit and capacity are set to the number of elements remaining in the this
buffer, starting from its position.
The following example demonstrates how to use the FloatBuffer slice()
method in Java.
The program creates a float array and uses it to create a buffer through the wrap()
method. The program then sets the buffer’s position to 3 and implements the FloatBuffer slice()
method. Since there are 6 elements in the original buffer and its position is 3, the limit of the new buffer is 3. The position of the new buffer is set to 0.
// Java program to demonstrate // mark() method import java.nio.*; import java.util.*; public class main { public static void main(String[] args) { try { float[] arr = { 11,22,33,44,55,66 }; //create an Int Buffer FloatBuffer buf = FloatBuffer.wrap(arr); //set position to index 3 buf.position(3); //create a slice FloatBuffer newbuf = buf.slice(); //display this buf System.out.println( "Original FloattBuffer"+ Arrays.toString(buf.array())); System.out.println( "\nPosition: "+ buf.position()); System.out.println( "\nLimit: " + buf.limit()); //display new float buffer System.out.println( "\nNew FloatBuffer"+ Arrays.toString(newbuf.array())); System.out.println( "\nPosition: "+ newbuf.position()); System.out.println( "\nLimit: " + newbuf.limit()); } catch (InvalidMarkException e) { System.out.println("New postion is less than the previous position"); System.out.println("Exception throws: " + e); } } }
RELATED TAGS
CONTRIBUTOR
View all Courses