title: ByteBuffer and Byte Array
body: <p><strong>Problem</strong></p>
  
  <p>I need to convert two ints and a string of variable length to bytes.</p>
  
  <p><strong>What I did</strong></p>
  
  <p>I converted each data type into a byte array and then added them into a byte buffer. Of which right after that I will copy that buffer to one byte array, as shown below.</p>
  
  <pre><code>byte[] nameByteArray = cityName.getBytes();
  byte[] xByteArray = ByteBuffer.allocate(4).putInt(x).array();
  byte[] yByteArray = ByteBuffer.allocate(4).putInt(y).array();
  ByteBuffer byteBuffer = ByteBuffer.allocate(nameByteArray.length + xByteArray.length + yByteArray.length);
  </code></pre>
  
  <p>Now that seems a little redundant. I can certainly place everything into byte buffer and convert that to a byte array. However, I have no idea what I string length is. So how would I allocate the byte buffer in this case? (to allocate a byte buffer you must specify its capacity)</p>