Buffer capacity() method in Java with Examples
The capacity() method of java.nio.Buffer Class is used to return this buffer’s capacity.
Syntax:
public final int capacity()
Return Value: The capacity of this buffer
Below are the examples to illustrate the capacity() method:
Examples 1:
// Java program to demonstrate // capacity() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocate(7); // putting the int to byte typecast // value in ByteBuffer bb.put((byte)20); bb.put((byte)30); bb.put((byte)40); bb.put((byte)50); // Typecasting ByteBuffer into Buffer Buffer bb1 = (Buffer)bb; // getting capacity of Buffer // using capacity() method int cap = bb1.capacity(); // display the result System.out.println("capacity is: " + cap); } } |
chevron_right
filter_none
Output:
capacity is: 7
Examples 2:
// Java program to demonstrate // capacity() method import java.nio.*; import java.util.*; public class GFG { public static void main(String[] args) { // Declaring and initializing byte array byte[] byt = { (byte)20, (byte)30, (byte)40, (byte)50, (byte)60 }; // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.wrap(byt); // Typecasting ByteBuffer into Buffer Buffer bb1 = (Buffer)bb; // getting capacity of Buffer // using capacity() method int cap = bb1.capacity(); // display the result System.out.println("capacity is: " + cap); } } |
chevron_right
filter_none
Output:
capacity is: 5
Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#capacity–
Recommended Posts:
- Buffer duplicate() method in Java with Examples
- Buffer arrayOffset() method in Java with Examples
- StringBuilder capacity() in Java with Examples
- Buffer remaining() methods in Java with Examples
- Buffer limit() methods in Java with Examples
- Buffer isDirect() methods in Java with Examples
- Buffer array() methods in Java with Examples
- Buffer hasArray() methods in Java with Examples
- Buffer hasRemaining() methods in Java with Examples
- Buffer position() methods in Java with Examples
- Buffer isReadOnly() methods in Java with Examples
- Buffer mark() methods in Java with Examples
- Buffer rewind() methods in Java with Examples
- Buffer reset() methods in Java with Examples
- Buffer clear() methods in Java with Examples
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

