Java (Android) BufferOverflowException on putInt

I try this code : byte arr[] = ByteBuffer.allocate(2).putInt(1).array() But it fails with a BufferOverflowException. Is 1 too big to be stored in 2 bytes ? Or is my problem somewhere else ?

Jon Skeet
people
quotationmark

Is 1 too big to be stored in 2 bytes ?

Well, an int is... putInt always writes 4 bytes. From the documentation for ByteBuffer.putInt

Throws:

BufferOverflowException - If there are fewer than four bytes remaining in this buffer

If you only want to put a two-byte integer, use putShort instead. If you want to store data in a variable-width encoding (where the space taken depends on the value), you'll probably need to write the code yourself.

people

See more on this question at Stackoverflow