Wednesday, July 3, 2024
HomeLanguagesJavaBuffer capacity() method in Java with Examples

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);
    }
}


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);
    }
}


Output:

capacity is: 5

Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/Buffer.html#capacity–

Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments