FloatBuffer slice() method in Java

A new FloatBuffer with the content as a shared subsequence of the original FloatBuffer can be created using the method slice() in the class java.nio.FloatBuffer. This method returns the new FloatBuffer that is read-only if the original buffer is read-only and direct if the original buffer is direct.

A program that demonstrates this is given as follows −


 Live Demo

import java.nio.*;
import java.util.*;
public class Demo {
   public static void main(String[] args) {
      int n = 5;
      try {
         FloatBuffer buffer1 = FloatBuffer.allocate(n);
         System.out.println("The Original FloatBuffer is: " + Arrays.toString(buffer1.array()));
         System.out.println("The position is: " + buffer1.position());
         System.out.println("The capacity is: " + buffer1.capacity());
         FloatBuffer buffer2 = buffer1.slice();
The Subsequence FloatBuffer is: " + Arrays.toString(buffer2.array()));          System.out.println("The position is: " + buffer2.position());          System.out.println("The capacity is: " + buffer2.capacity());       } catch (IllegalArgumentException e) {          System.out.println("Error!!! IllegalArgumentException");       } catch (ReadOnlyBufferException e) {          System.out.println("Error!!! ReadOnlyBufferException");       }    } }

The output of the above program is as follows −


The Original FloatBuffer is: [4.5, 1.2, 3.9, 0.0, 0.0]
The position is: 3
The capacity is: 5
The Subsequence FloatBuffer is: [4.5, 1.2, 3.9, 0.0, 0.0]
The position is: 0
The capacity is: 2

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started