- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
ByteBuffer allocateDirect() method in Java
A direct byte buffer can be allocated using the method allocateDirect() in the class java.nio.ByteBuffer. This method requires a single parameter i.e. the capacity in bytes and it returns the direct byte buffer. If the capacity provided is negative, then the IllegalArgumentException is thrown.
A program that demonstrates this is given as follows −
Example
import java.nio.*; import java.util.*; public class Demo { public static void main(String[] args) { int n = 5; try { ByteBuffer buffer = ByteBuffer.allocateDirect(n); byte[] byteValues = { 7, 1, 6, 3, 8 }; buffer = ByteBuffer.wrap(byteValues); System.out.println("The direct ByteBuffer is: " + Arrays.toString(buffer.array())); System.out.println("
The state of the ByteBuffer is: "); System.out.println(buffer.toString()); } catch (IllegalArgumentException e) { System.out.println("Error!!! IllegalArgumentException"); } catch (ReadOnlyBufferException e) { System.out.println("Error!!! ReadOnlyBufferException"); } } }
Output
The direct ByteBuffer is: [7, 1, 6, 3, 8] The state of the ByteBuffer is: java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
Advertisements