1

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?

1
  • 2
    No, Integer.SIZE is 32, so that's creating a 4-byte buffer. And no, it's not returning a Byte, it's returning a ByteBuffer. Commented Apr 18, 2017 at 18:12

1 Answer 1

2

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); 
Sign up to request clarification or add additional context in comments.

Comments