Saturday, December 28, 2024
Google search engine
HomeLanguagesJavaIntBuffer allocate() method in Java

IntBuffer allocate() method in Java

The allocate() method of java.nio.IntBuffer Class is used to allocate a new int 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 IntBuffer allocate(int capacity)

Parameter: This method takes the new buffer’s capacity, in int, as a parameter.

Return Value: This method returns the new int buffer.

Exception: This method throws the IllegalArgumentException if the capacity is a negative integer.

Below program illustrates the allocate() method:

Examples 1:




// 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 IntBuffer
        int Capacity = 10;
  
        // Creating the IntBuffer
  
        // creating object of intbuffer
        // and allocating size capacity
        IntBuffer ib = IntBuffer.allocate(Capacity);
  
        // putting the value in intbuffer
        ib.put(11);
        ib.put(2, 19);
  
        System.out.println("IntBuffer: "
                           + Arrays.toString(ib.array()));
    }
}


Output:

IntBuffer: [11, 0, 19, 0, 0, 0, 0, 0, 0, 0]

Examples 2: To demonstrate IllegalArgumentException




// 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 IntBuffer
        // by negative integer
        int Capacity = -10;
  
        // Creating the IntBuffer
        try {
  
            // creating object of intbuffer
            // and allocating size with negative integer
            System.out.println("Trying to allocate a Negative Integer");
  
            IntBuffer ib = IntBuffer.allocate(Capacity);
        }
        catch (IllegalArgumentException e) {
            System.out.println("Exception thrown: " + e);
        }
    }
}


Output:

Trying to allocate a Negative Integer
Exception thrown: java.lang.IllegalArgumentException
Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments