Reputation:
into a Java application I found this line:
ByteBuffer b = ByteBuffer.allocate(Integer.SIZE / 8);
It creats a ByteBuffer object (that I think is used to read and write single byte. So what it means? That I can put and read only bytes in this object?).
So the ByteBuffer.allocate() method seems to be something like a factory method that return a Byte.
But what exactly is allocating passing the Integer.SIZE / 8 value as input parameter?
Upvotes: 1
Views: 8589
Reputation: 131346
what exactly is allocating passing the Integer.SIZE / 8 value as input parameter?
It is creating a ByteBuffer
instance with a 4 bytes capacity(32/8).
If you put more than one integer (or 4 bytes) in the ByteBuffer
instance, a java.nio.BufferOverflowException
is thrown.
It creates a ByteBuffer object (that I think is used to read and write single byte. So what it means? That I can put and read only bytes in this object?).
You can put in byte
but also all other primitive types except boolean : int
, long
, short
, float
and double
.
put(byte b)
method writes a byte.
putInt(int value)
writes an int.
and so for..
So the ByteBuffer.allocate() method seems to be something like a factory method that return a Byte.
It is indeed a factory method but not to return a Byte
but a ByteBuffer
instance.
In fact, the ByteBuffer
class is not instantiable from the client class : it is an abstract class.
So ByteBuffer.allocate()
instantiates a implementation of the ByteBuffer
class and returns it to the client :
ByteBuffer allocate = ByteBuffer.allocate(Integer.SIZE / 8);
So you can write in :
allocate.putInt(1);
Upvotes: 2