Open In App

DoubleBuffer allocate() method in Java With Examples

Improve
Improve
Like Article
Like
Save
Share
Report

The allocate() method of java.nio.DoubleBuffer Class is used to allocate a new double buffer next to the existing buffer. The new buffer’s position will be zero. Its limit will be its capacity. Its mark will be undefined. And each of its elements will be initialized to zero. It will have a backing array, and its array offset will be zero.
Syntax: 
 

public static DoubleBuffer allocate(int capacity)

Parameter: This method takes the new buffer’s capacity, in double, as a parameter.
Return Value: This method returns the new double buffer.
Exception: This method throws the IllegalArgumentException if the capacity is a negative integer.
Below program illustrates the allocate() method:
Examples 1:
 

Java




// Java program to demonstrate
// allocate() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the DoubleBuffer
        int capacity = 10;
 
        // Creating the DoubleBuffer
 
        // creating object of Doublebuffer
        // and allocating size capacity
        DoubleBuffer db = DoubleBuffer.allocate(capacity);
 
        // putting the value in Doublebuffer
        db.put(8.56F);
        db.put(2, 9.61F);
 
        System.out.println("DoubleBuffer: "
                           + Arrays.toString(db.array()));
    }
}


Output: 

DoubleBuffer: [8.5600004196167, 0.0, 9.609999656677246, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]

 

Examples 2: To demonstrate IllegalArgumentException 
 

Java




// Java program to demonstrate
// allocate() method
 
import java.nio.*;
import java.util.*;
 
public class GFG {
    public static void main(String[] args)
    {
 
        // Declaring the capacity of the DoubleBuffer
        // by negative integer
        int capacity = -10;
 
        // Creating the DoubleBuffer
        try {
 
            // creating object of Doublebuffer
            // and allocating size with negative integer
            System.out.println("Trying to allocate a negative integer");
 
            DoubleBuffer db = DoubleBuffer.allocate(capacity);
        }
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown: " + e);
        }
    }
}


Output

Trying to allocate a negative integer
Exception thrown: java.lang.IllegalArgumentException: capacity < 0: (-10 < 0)


Last Updated : 21 May, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads